嘿,我正在尝试让 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)
我确定我设置了正确的权限,并且第一个视频可以正常创建。仅在第二次录制时才会出现此问题。