Android 录屏操作
本文主要介绍android中如何通过MediaRecorder实现录屏操作的.
1: 申请权限
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
以上是录音以及存储的权限,另外需要动态申请录屏的权限.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
service = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
Intent screenCaptureIntent = service.createScreenCaptureIntent();
startActivityForResult(screenCaptureIntent, 1001);
}
如上操作,点击后会弹出提示:
点击立即开始即可.
2: 获取MediaProjection
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && resultCode == RESULT_OK) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
mediaProjection = service.getMediaProjection(resultCode, data);
}
Toast.makeText(this, "申请权限成功", Toast.LENGTH_SHORT).show();
}
}
3: 创建MediaRecorder
创建mediarRecorder实例,设置相关参数.
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setOutputFile("sdcard/test.mp4");
mediaRecorder.setVideoSize(1920, 2560);
mediaRecorder.setVideoFrameRate(90);
4: 创建VirtualDisplay并开始录制
VirtualDisplay 通过mediaProjection关联创建.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
try {
mediaRecorder.prepare();
isRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
Surface surface = mediaRecorder.getSurface();
virtualDisplay = mediaProjection.createVirtualDisplay("ScreenRecording", 1920, 2560, 60,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, null);
mediaRecorder.start();
}
5: 结束录制
private void stopRecord() {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (virtualDisplay!=null) virtualDisplay.release();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mediaProjection != null) mediaProjection.stop();
}
}
最后将相关资源释放即可.