问题
I wrote a class that shall make it possible to record an audio, save it to the sd card and then play the result. Here is my code:
public void recordAudio(final String fileName) {
final MediaRecorder recorder = new MediaRecorder();
recorder.reset();
ContentValues values = new ContentValues(3);
values.put(MediaStore.MediaColumns.TITLE, fileName);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
final String myPath = Environment.getExternalStorageDirectory() + "/MyOwnQuiz/" + fileName + ".3gp";
recorder.setOutputFile(myPath);
try {
recorder.prepare();
} catch (Exception e){
e.printStackTrace();
}
final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Record audio");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setButton (DialogInterface.BUTTON_POSITIVE,"Stop recording", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mProgressDialog.dismiss();
recorder.stop();
recorder.release();
MediaPlayer mp = new MediaPlayer();
File f = new File(myPath);
if(f.exists()){
try{
mp.setDataSource(myPath);
mp.prepare();
}catch(IOException e){
}
mp.start();
}
}
});
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface p1) {
recorder.stop();
recorder.release();
}
});
recorder.start();
mProgressDialog.show();
}
The recording works fine. The recorded file also appears on my sd card, just as I want it to be. But can't get the app to play this recorded audio. As you can see I tried it just in the BUTTON_POSITIV. After pressing the stop button the audio shall be saved and the audio played once. What am I doing wrong?
This is how I am calling the function:
Calendar myCal = Calendar.getInstance();
String myString = myCal.getTime().toString();
recordAudio(myString);
回答1:
Try passing the recorded file's descriptor to the setDataSource() method instead :
File f = new File(myPath);
if(f.exists()){
FileInputStream fis = new FileInputStream(f);
FileDescriptor fileD = fis.getFD();
try{
mp.setDataSource(fileD);
mp.prepare();
}catch(IOException e){
}
mp.start();
}
来源:https://stackoverflow.com/questions/28971334/record-audio-and-play-it-afterwards