在网上找了好久都没有找到合适的代码,曾想过用Timer,但TimeTask过程复杂,不知停止后如何继续录音。后来看到了MediaRecorder的reset() 方法,可以重置参数,继续录音,结合setMaxDuration和 MediaRecorder.OnInfoListener来监听当时间间隔达到时捕获事件变可实现音频文件每隔一段时间存储一次。
啥也不说了,奉上代码
//开始
public void start(View view){
Date date = new Date();
startRecording((int) (date.getTime()/1000));
start.setEnabled(false);
stop.setEnabled(true);
// Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
//开始录音
public void startRecording(int datetime){
myAutoRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAutoRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAutoRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAutoRecorder.setAudioSamplingRate(44100);
myAutoRecorder.setAudioChannels(1);
myAutoRecorder.setMaxDuration(30000);// set max duration
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath()+"/myrecording_"+datetime+".3gp";
myAutoRecorder.setOutputFile(outputFile);
myAutoRecorder.setOnInfoListener(this);
try{
myAutoRecorder.prepare();
myAutoRecorder.start();
}catch (IllegalStateException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
//listenning the max_duration_reached
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
Log.v("AUDIOCAPTURE","Maximum Duration Reached");
File audioFile = new File(outputFile);
myAutoRecorder.reset();//reset
Date date = new Date();
startRecording((int) (date.getTime()/1000));
}
注意:
类实现MediaRecorder.OnInfoListener接口