问题
I'm trying to make it to where I can record the users voice and play it back in the same activity using the MediaRecorder and AudioTrack. I just don't understand how to write the file to AudioTrack. I've read the documents on both and simply can't figure it out. Any help would be appreciated. Here's my code so far, it's not complete. The only buttons you need to read are recordButton and playbackButton. Thanks!
private File outputFile = null;
private AudioTrack voice = null;
private MediaRecorder recorder = null;
....
// Setup recorder...
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// Setup record file...
outputFile = getFileStreamPath("output.amr");
recorder.setOutputFile(outputFile.getAbsolutePath());
public void onClick(View v){
switch(v.getId()) {
case R.id.next_button:
giveSentence();
break;
case R.id.repeat_button:
// playSentence();
break;
case R.id.recordButton:
if (!recording){
recordButton2.setBackgroundResource(android.R.drawable.button_onoff_indicator_on);
recording = true;
recorder.reset();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outputFile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.start();
}
else if(recording) {
recordButton2.setBackgroundResource(android.R.drawable.button_onoff_indicator_off);
recording = false;
recorder.stop();
}
break;
case R.id.playbackButton:
Music.playSentence(this, outputFile);
break;
case R.id.slowButton:
if(!slowedSpeech) {
slowButton2.setBackgroundResource(android.R.drawable.ic_dialog_alert);
slowedSpeech = true;
// slowspeech();
}
else if(slowedSpeech) {
slowButton2.setBackgroundResource(android.R.drawable.ic_menu_recent_history);
slowedSpeech = false;
// noSlowSpeech();
}
break;
}
}
回答1:
what do you mean by write file to audio track? you don't need to write any file to audio track, you set the audio source, the recorder will create audio track and read pcm data from the audio source, then encoder the data, write the data into the output file.
来源:https://stackoverflow.com/questions/6616619/android-mediarecorder-to-audiotrack-recording-and-playback