다음은 안드로이드에서 MediaRecorder와 MediaPlayer를 이용하여 소리를 녹음하고 재생하는 예시이다.
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
// Example
public class MyVoicePlayer {
private static final String TAG = "KugiVoicePlayer";
private static MyVoicePlayer Instance = null;
private static String filePath = "";
private static MediaRecorder recorder = null;
private static MediaPlayer player = null;
public static MyVoicePlayer GetInstance()
{
if ( Instance == null )
{
Instance = new MyVoicePlayer();
}
return Instance;
}
private MyVoicePlayer()
{
File file = Environment.getRootDirectory();
filePath = file.getAbsolutePath() + String.format("/myvoice0001.mp4");
}
// 재생
private static void _playRec()
{
if ( player != null )
{
player.stop();
player.release();
player = null;
}
try {
player = new MediaPlayer();
player.setDataSource(filePath);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 녹음 중지
private static void _stopRec()
{
if ( recorder == null ) {
return;
}
recorder.stop();
recorder.release();
recorder = null;
}
// 재생 중지
private static void _stop()
{
if ( player == null ) {
return;
}
player.stop();
player.release();
player = null;
}
// 녹음
private static void _record()
{
if ( recorder != null ) {
recorder.stop();
recorder.release();
recorder = null;
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(filePath);
try {
recorder.prepare();
recorder.start();
Log.i(TAG, "recording start");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
setAudioSource() : 소리를 어디서부터 받아올지 설정한다.
마이크를 녹음하거나 통화 중 목소리 녹음, 통화 중 발신자 목소리만 녹음, 통화 중 수신자 목소리만 녹음 등을 결정한다.
setOutputFormat() : 녹음 파일의 데이터 형식(format)을 설정한다.
setAudioEncoder() : 인코더(코덱)을 설정한다.
setOutputFile() : 녹음 파일의 경로 및 이름을 설정한다.