Android系统录屏代码
时间: 2023-05-22 08:06:39 浏览: 347
android录屏代码简单例子
我可以为您提供Android系统录屏的代码:
MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
Intent intent = mediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(intent, REQUEST_CODE_SCREEN_CAPTURE);
在onActivityResult方法中,可以获取到MediaProjection:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_SCREEN_CAPTURE && resultCode == RESULT_OK) {
mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
}
}
接下来,使用MediaProjection可以获取到屏幕帧数据,并通过MediaCodec进行编码:
mImageReader = ImageReader.newInstance(mScreenWidth, mScreenHeight, PixelFormat.RGBA_8888, 1);
mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen_capture", mScreenWidth, mScreenHeight, mDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaCodec.configure(mMediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
通过MediaMuxer将编码后的数据写入文件:
while (!mIsQuit) {
int index = mMediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);
if (index == MediaCodec.INFO_TRY_AGAIN_LATER) {
// no output available yet
} else if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
if (mMuxerStarted) {
throw new RuntimeException("format changed twice");
}
mMediaFormat = mMediaCodec.getOutputFormat();
mMuxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
mTrackIndex = mMuxer.addTrack(mMediaFormat);
mMuxer.start();
mMuxerStarted = true;
} else if (index < 0) {
// unexpected result from dequeueOutputBuffer
} else {
ByteBuffer encodedData = mMediaCodec.getOutputBuffer(index);
if (encodedData == null) {
throw new RuntimeException("couldn't fetch buffer at index " + index);
}
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
// The codec config data was pulled out and fed to the muxer when we got
// the INFO_OUTPUT_FORMAT_CHANGED status. Ignore it.
bufferInfo.size = 0;
}
if (bufferInfo.size != 0) {
if (!mMuxerStarted) {
throw new RuntimeException("muxer hasn't started");
}
encodedData.position(bufferInfo.offset);
encodedData.limit(bufferInfo.offset + bufferInfo.size);
mMuxer.writeSampleData(mTrackIndex, encodedData, bufferInfo);
}
mMediaCodec.releaseOutputBuffer(index, false);
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
break; // out of while
}
}
}
最后,记得在结束时进行相关资源的释放:
mMediaProjection.stop();
mVirtualDisplay.release();
mMediaCodec.stop();
mMediaCodec.release();
mMuxer.stop();
mMuxer.release();
阅读全文