嘿我试图让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)
我确定我设置了正确的权限,并且第一个视频创建得很好。只有在第二次进行录制时才会出现此问题。
答案 0 :(得分:1)
问题是你正在执行这两行代码:
initRecorder();
prepareRecorder();
在stopRecording()
功能结束时,再次在startRecording()
功能中。
如果您在设置音频源后尝试在mediaRecorder.setAudioSource
中呼叫initRecorder()
,则会收到IllegalStateException
,因为它处于错误的状态。
如果您查看the Android MediaRecorder reference page上的状态图,您会看到MediaRecorder
必须处于初始状态才能调用setAudioSource()
,但是您的stopRecording()
处于准备状态已调用setAudioSource()
,您尝试再次致电.bash_profile
。