需求
使用android手机录音
了解MediaRecorder
代码语言:javascript复制 mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(newFileName());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
步骤
- 设定声音来源。这里指定为 麦克风
- 指定输出格式 。
- 指定输出文件。
- 指定音频编码格式。
- 预备。
- 启动录音。
代码
配合启动录音的过程,就会有终止录音的过程,代码:
mRecorder.stop();
mRecorder.release(); mRecorder = null; 结束,并释放资源。
播放
录音完成后,总得要听听吧。我们看播放的过程:
代码语言:javascript复制mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(fileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
终止播放呢
代码语言:javascript复制 mPlayer.release();
mPlayer = null;
完整代码
代码语言:javascript复制class SoundRecorder {
MediaRecorder mRecorder;
boolean isRecording;
public void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(newFileName());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
public void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public String newFileName() {
String mFileName = Environment.getExternalStorageDirectory()
.getAbsolutePath();
String s = new SimpleDateFormat("yyyy-MM-dd hhmmss")
.format(new Date());
return mFileName = "/rcd_" s ".3gp";
}
}
public class SoundPlayer {
MediaPlayer mPlayer;
public void startPlaying(String fileName) {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(fileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
public void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
}