嘿,我正在尝试使用 mediarecorder api 在 android lolipop 中录制截屏应用程序。问题是我的应用程序表现得很奇怪。每当我在 VideoRecorder 类上调用开始录制时,即使对视频大小和输出文件等配置进行硬编码,手机也会重新启动。该应用程序以前运行良好 - 将内容保存在正确的位置,视频本身看起来不错,但后来我更改了代码中的某些内容,现在它不起作用。知道我错过了什么吗?这是我的代码:
public class VideoRecorder {
private int screenDensity, screenHeight, screenWidth;
private MediaRecorder mMediaRecorder;
private VirtualDisplay mVirtualDisplay;
private MediaProjection mediaProjection;
private String directory, filename;
private Display defaultDisplay = null;
private DisplayMetrics metrics;
public VideoRecorder(Display defaultDisplay) {
//this.defaultDisplay = defaultDisplay;
//metrics = new DisplayMetrics();
//defaultDisplay.getMetrics(metrics);
//screenDensity = metrics.densityDpi;
// screenHeight = metrics.heightPixels;
// screenWidth = metrics.widthPixels;
}
void prepareVideoRecorder() {
initRecorder();
prepareRecorder();
}
private void initRecorder() {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(540, 888);
// mMediaRecorder.setOutputFile(directory + "/" + filename + ".mp4");
mMediaRecorder.setOutputFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsoluteFile() + "/recorderrsr.mp4");
}
void startRecording(MediaProjection mediaProjection) {
mMediaRecorder = new MediaRecorder();
initRecorder();
prepareRecorder();
this.mediaProjection = mediaProjection;
mMediaRecorder.start();
mVirtualDisplay = createVirtualDisplay();
}
private VirtualDisplay createVirtualDisplay() {
return mediaProjection.createVirtualDisplay("MainActivity",
540, 888, 240,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
}
void setFilename(String filename) {
this.filename = filename;
}
void setDirectory(String directory) {
this.directory = directory;
}
void stopRecording() {
mMediaRecorder.stop();
mMediaRecorder.reset();
if (mediaProjection != null) {
mediaProjection.stop();
mediaProjection = null;
}
if (mMediaRecorder != null) {
mMediaRecorder.release();
mMediaRecorder = null;
}
if (mVirtualDisplay != null) {
mVirtualDisplay.release();
}
}
private void prepareRecorder() {
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void release() {
mMediaRecorder.release();
}
}
我确定该位置存在并且我拥有正确的权限 - 正如我之前所说的那样,该应用程序运行良好。感谢乔恩的帮助