Android录屏代码
时间: 2023-05-22 18:06:48 浏览: 284
以下是在 Android 平台上实现录屏的代码,你可以参考:
MediaRecorder mediaRecorder;
VirtualDisplay virtualDisplay;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
int screenHeight = Util.getScreenHeight(this);
int screenWidth = Util.getScreenWidth(this);
mediaRecorder = new MediaRecorder();
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(5 * screenWidth * screenHeight);
mediaRecorder.setVideoFrameRate(30);
mediaRecorder.setVideoSize(screenWidth, screenHeight);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "test.mp4");
mediaRecorder.setOutputFile(file.getAbsolutePath());
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
// Create a virtual display
DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
virtualDisplay = displayManager.createVirtualDisplay("MainActivity", screenWidth, screenHeight, 50, null, DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, mediaRecorder.getSurface(), null, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
mediaRecorder.release();
virtualDisplay.release();
}
请注意,你需要在 AndroidManifest.xml 文件中添加权限:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
希望对你有帮助,如有其他问题,欢迎继续提问。
阅读全文