Intent screenRecordIntent = mediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(screenRecordIntent,100);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
//MediaProjection—>产生录屏数据
mediaProjection = mediaProjectionManager.getMediaProjection
(resultCode, data);
}
}
对数据进行 h264 编码
通过 MediaProjection 获取到的 YUV 裸数据,我们先需要对其进行 h264 编码,此时我们使用原生 MediaCodec 进行硬件编码
public void start(MediaProjection mediaProjection){
this.mediaProjection = mediaProjection;
// 配置 MediaCodec
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC,width,height);
// 颜色格式
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 400_000);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
// 设置触发关键帧的时间间隔为 2 s
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2);
// 创建编码器
try {
mediaCodec = MediaCodec.createEncoderByType(“video/avc”);
mediaCodec.configure(mediaFormat,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
Surface surface = mediaCodec.createInputSurface();
mediaProjection.createVirtualDisplay(TAG,width,height,1, DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC
,surface,null,null);
} catch (IOException e) {
e.printStackTrace();
}
start();
}
@Override
public void run() {
isLiving = true;
mediaCodec.start();
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
while (isLiving){
//若时间差大于 2 s,则通知编码器,生成 I 帧
if (System.currentTimeMillis() - timeStamp >= 2000){
// Bundle 通知 Dsp
Bundle msgBundle = new Bundle();
msgBundle.putInt(MediaCodec.PA