录制音频并随后播放

时间:2015-03-10 18:24:24

标签: android android-mediaplayer android-sdcard

我写了一个类,可以录制音频,将其保存到SD卡然后播放结果。这是我的代码:

 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();


    }

录音效果很好。录制的文件也出现在我的SD卡上,就像我想要的那样。但无法让该应用播放此录制的音频。正如您所看到的,我只是在BUTTON_POSITIV中尝试过它。按下停止按钮后,音频将被保存,音频播放一次。我做错了什么?

这就是我调用函数的方式:

Calendar myCal = Calendar.getInstance();
                            String myString = myCal.getTime().toString();
                            recordAudio(myString);

1 个答案:

答案 0 :(得分:0)

尝试将录制文件的描述符传递给setDataSource()方法:

 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();
}