当我按“录制”按钮6秒钟后,Android应用程序崩溃

时间:2019-10-09 20:19:39

标签: java android

                Toast.makeText(MainActivity.this, "Recording...", Toast.LENGTH_SHORT).show();
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //Do something after 6s
                        Toast.makeText(MainActivity.this, "Stopped Recording", Toast.LENGTH_SHORT).show();

                        mediaRecorder.stop();
                        mediaRecorder.release();
                        setupMediaRecorder();
                    }
                }, 6000);

开始录制后6秒钟,应用程序崩溃了,这是我的设置媒体录制器功能:

   private void setupMediaRecorder()
{
    mediaRecorder= new MediaRecorder();
    mediaRecorder.setAudioSamplingRate(8000);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.OGG);
   // mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.OGG);
    mediaRecorder.setOutputFile(pathSave);
}

logcat: 错误发生在mediaRecorder.Stop();处。在处理程序中

2019-10-10 01:11:49.942 21574-21574/com.example.parkinsonsdisease E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parkinsonsdisease, PID: 21574
java.lang.IllegalStateException
    at android.media.MediaRecorder._stop(Native Method)
    at android.media.MediaRecorder.stop(MediaRecorder.java:1378)
    at com.example.parkinsonsdisease.MainActivity$1$1.run(MainActivity.java:93)

3 个答案:

答案 0 :(得分:0)

请参阅文档:

  

公共无效站()

     

...

     

投掷

     

IllegalStateException,如果在start()之前调用

答案 1 :(得分:0)

就像@LeoLeontev提到的,很可能是因为您没有给prepare()start()打电话。

任何对stop()的调用都必须在对start()的调用之前,并且start()必须在对prepare()的调用之前。

换句话说,

private void setupMediaRecorder()
{
    mediaRecorder= new MediaRecorder();
    ...
    mediaRecorder.prepare();
}

private void startRecording()
{
    mediaRecorder.start();
}

请参见以下图表以供参考: MediaRecorder State Diagram

另外,请参见MediaRecorder文档here

答案 2 :(得分:0)

按照MediaRecorder State diagram中给出的步骤操作后,我按此顺序使用了设置编码器和输出格式,并解决了上面面临的问题:

    private void setupMediaRecorder()
{
    mediaRecorder= new MediaRecorder();
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setAudioSamplingRate(8000);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    mediaRecorder.setOutputFile(pathSave);

}