重新使用MediaRecorder实例时出现IllegalStateException异常



嘿,我想让MediaRecorder记录我屏幕上的内容。当我第一次录制时,它可以工作,但当我第二次尝试录制屏幕时,它就失败了。以下是相关代码:

void startRecording(String directory,String filename,MediaProjection mediaProjection) {
    this.mediaProjection=mediaProjection;
    this.directory=directory;
    this.filename=filename;
    initRecorder();
    prepareRecorder();
    virtualDisplay = createVirtualDisplay();
    mediaRecorder.start();
}
void stopRecording() {
    mediaRecorder.stop();
    mediaRecorder.reset();
    if (virtualDisplay != null) {
        virtualDisplay.release();
    }
    if (mediaProjection != null) {
        mediaProjection.stop();
        mediaProjection = null;
    }
    initRecorder();
    prepareRecorder();
}
void setScreen(int screenWidth, int screenHeight, int screenDensity) {
    this.screenWidth = screenWidth;
    this.screenHeight = screenHeight;
    this.screenDensity = screenDensity;
}
void prepareRecorder() {
    try {
        mediaRecorder.prepare();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
void initRecorder() {
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediaRecorder.setVideoEncodingBitRate(512 * 1000);
    mediaRecorder.setVideoFrameRate(30);
    mediaRecorder.setVideoSize(screenWidth, screenHeight);
    mediaRecorder.setOutputFile(directory + "/" + filename + ".mp4");
    //mediaRecorder.setOutputFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()+"/vitalij.mp4");
}

所以在我的活动中,我创建了这个类的一个新实例,然后按下按钮后,startRecording方法被调用。然后用户可以按下停止录制,这将调用stopRecording方法。当应用程序被销毁时,我释放mediaRecorder对象。这是我得到的错误:

 Caused by: java.lang.IllegalStateException
        at android.media.MediaRecorder.setAudioSource(Native Method)
        at com.example.xxx.myapplication.VideoRecorder.initRecorder(VideoRecorder.java:77)
        at com.example.xxx.myapplication.VideoRecorder.startRecording(VideoRecorder.java:30)
        at com.example.xxx.myapplication.MainActivity.onActivityResult(MainActivity.java:134)

我确信我有正确的权限设置和第一个视频被创建好。此问题仅在第二次录制时发生。

问题是你正在执行这两行代码:

initRecorder();
prepareRecorder();

stopRecording()函数的末尾,在startRecording()函数的末尾。

当您尝试在initRecorder()中调用mediaRecorder.setAudioSource时,音频源已经设置好,您会得到IllegalStateException,因为它处于不正确的状态。

如果你看Android MediaRecorder参考页面上的状态图,你会看到MediaRecorder必须处于初始状态才能调用setAudioSource(),但你的stopRecording()被调用后处于准备状态,你再次尝试调用setAudioSource()

相关内容

  • 没有找到相关文章

最新更新