简单屏幕录制截屏工具

news/2024/10/31 5:31:29/

很久没写了,随便写写~~

额,这是一个很简单的截屏工具,用的是Android系统的MediaProjectionManager实现截屏录制功能

使用到的主要类:

说明
MediaProjectionManagerMediaProjection管理
MediaProjection授予捕获屏幕或记录系统音频的功能
VirtualDisplay个人理解类似虚拟屏幕?捕获屏幕后将数据输出到虚拟屏幕 然后可以获取视频的信息,指定输出的位置等
ImageReader这个类被允许直接从Surface接收渲染的图像数据
MediaRecorder用于将音视频编码输出

流程:

  • 1.申请录屏screenCaptureIntent
  • 2.调用activity的 startActivityForResult(screenCaptureIntent,code);需要用户允许
  • 3.在onActivityResult获取屏幕录制的操作对象mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);
  • 4.MediaProjection + VirtualDisplay + Surface(根据情况使用提供者) 实现录屏截屏功能

使用:

1.在Activity的onCreate下创建

screenshotRecordUtil = new ScreenshotRecordUtil();
screenshotRecordUtil.screenCaptureIntent(this, new ScreenshotRecordUtil.ScreenshotRecordCallback() {@Overridepublic void onScreenshotSuccess(String path, Bitmap bitmap) {//path目前没写(没有保存文件,有需求自行在ScreenshotRecordUtil里startCapture方法实现),//这里是直接获取的bitmap显示//在主线程更新UIrunOnUiThread(new Runnable() {@Overridepublic void run() {//Glide.with(Live2Activity.this).load(bitmap).into(image);}});}@Overridepublic void onScreenshotFailure() {//截图失败}@Overridepublic void onRecordStart() {//录屏开始//LogUtils.d("录屏开始:");}@Overridepublic void onRecordStop(String path) {//录屏结束//LogUtils.d("录屏结束:"+path);}});

2.实现onActivityResult方法

 @RequiresApi(api = Build.VERSION_CODES.O)@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == ScreenshotRecordUtil.REQUEST_SHOT_CODE && resultCode == RESULT_OK) {// 获取申请截屏结果screenshotRecordUtil.setUpImageProjection(Live2Activity.this, resultCode, data);} else if (requestCode == ScreenshotRecordUtil.REQUEST_RECORD_CODE && resultCode == RESULT_OK) {// 获取申请录屏结果//录屏文件存储目录地址String root = Environment.getExternalStorageDirectory() + AppConstants.PATH_VIDEO);File appDir = new File(root);if (!appDir.exists()) {appDir.mkdirs();}//创建文件File file = new File(appDir, System.currentTimeMillis() + ".mp4");screenshotRecordUtil.setUpVideoProjection(Live2Activity.this, resultCode, data, file);}}

3.点击按钮,截屏

   /*** 截取屏幕* REQUEST_SHOT_CODE 是请求码,和你的重复了可以自己更改*/@OnClick(R.id.btn_screenshot)void screenshot() {screenshotRecordUtil.screenCapture(ScreenshotRecordUtil.REQUEST_SHOT_CODE);}

4.点击按钮,录屏

   /*** 录屏*/@OnClick(R.id.btn_recording)void onClickRecording() {if (screenshotRecordUtil.isRecording()) {screenshotRecordUtil.mediaRecorderStop();} else {screenshotRecordUtil.screenCapture(ScreenshotRecordUtil.REQUEST_RECORD_CODE);}}

ScreenshotRecordUtil 类:


import static android.content.Context.WINDOW_SERVICE;import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;/*** 截屏录屏工具* <p>* 1.申请录屏Intent* <p>* 2.然后调用activity的 startActivityForResult(screenCaptureIntent,code);* <p>* 3.onActivityResult获取屏幕录制的操作对象* mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);* <p>* 4.MediaProjection + VirtualDisplay + Surface(根据情况使用提供者) 实现录屏截屏功能*/
public class ScreenshotRecordUtil {private static final String TAG = ScreenshotRecordUtil.class.getSimpleName();public static final int REQUEST_SHOT_CODE = 10011;//截屏请求回调codepublic static final int REQUEST_RECORD_CODE = 10012;//录屏请求回调codeprivate MediaRecorder mMediaRecorder;                                                           //MediaRecorder屏幕录制 需求场景是把屏幕录制成文件,录屏直播则使用MediaCodec或者大名鼎鼎的FFmpegprivate ImageReader mImageReader;                                                               //获取屏幕渲染得到Imageprivate MediaProjectionManager mediaProjectionManager;                                          //系统提供的一个录屏服务private MediaProjection mMediaProjection;                                                       //屏幕录制的操作对象private VirtualDisplay mVirtualDisplay;                                                         //虚拟屏幕——VirtualDisplayprivate String mVideoPath;                                                                      //录像输入地址private Activity activity;private Intent screenCaptureIntent;private ScreenshotRecordCallback screenshotRecordCallback;/*** 申请录屏Intent*/public void screenCaptureIntent(Activity activity, ScreenshotRecordCallback screenshotRecordCallback) {this.activity = activity;this.screenshotRecordCallback = screenshotRecordCallback;this.mediaProjectionManager = (MediaProjectionManager) activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);this.screenCaptureIntent = mediaProjectionManager.createScreenCaptureIntent();}/*** 调用activity的 startActivityForResult*/public void screenCapture(int code) {this.activity.startActivityForResult(screenCaptureIntent, code);}/*** 获取屏幕截图** @param activity   activity* @param resultCode onActivityResult返回的 resultCode* @param resultData onActivityResult返回的 resultData*/public void setUpImageProjection(Activity activity, int resultCode, Intent resultData) {//创建mImageReader,用于获取VirtualDisplay的imageDisplayMetrics displayMetrics = new DisplayMetrics();WindowManager windowManager = (WindowManager) activity.getSystemService(WINDOW_SERVICE);windowManager.getDefaultDisplay().getMetrics(displayMetrics);int width = displayMetrics.widthPixels;int height = displayMetrics.heightPixels;Log.e(TAG, "displayMetrics width=" + width + ", height=" + height);this.mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);//获取屏幕录制的操作对象this.mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);//创建虚拟屏幕,使用ImageReader提供的Surface//VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR:当没有内容显示时,允许将内容镜像到专用显示器上。//VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY:仅显示此屏幕的内容,不镜像显示其他屏幕的内容。//VIRTUAL_DISPLAY_FLAG_PRESENTATION:创建演示文稿的屏幕。//VIRTUAL_DISPLAY_FLAG_PUBLIC:创建公开的屏幕。//VIRTUAL_DISPLAY_FLAG_SECURE:创建一个安全的屏幕this.mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture",width, height,displayMetrics.densityDpi,DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,mImageReader.getSurface(), null, null);//这里稍稍作了个延时,立马取的话 mImageReader.acquireLatestImage()可能为空ThreadUtils.executeByCachedWithDelay(new ThreadUtils.SimpleTask<Object>() {@Overridepublic Object doInBackground() throws Throwable {startCapture();return null;}@Overridepublic void onSuccess(Object result) {}}, 100, TimeUnit.MILLISECONDS);}/*** 屏幕录制** @param activity   activity* @param resultCode onActivityResult返回的 resultCode* @param resultData onActivityResult返回的 resultData* @param file       录制输出文件*/public void setUpVideoProjection(Activity activity, int resultCode, Intent resultData, File file) {//创建mImageReader,用于获取VirtualDisplay的imageDisplayMetrics displayMetrics = new DisplayMetrics();WindowManager windowManager = (WindowManager) activity.getSystemService(WINDOW_SERVICE);windowManager.getDefaultDisplay().getMetrics(displayMetrics);int width = displayMetrics.widthPixels;int height = displayMetrics.heightPixels;Log.e(TAG, "displayMetrics width=" + width + ", height=" + height);initMediaRecorder(file, width, height);//获取屏幕录制的操作对象this.mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);//创建虚拟屏幕 需要在mMediaRecorder.prepare();后,否则mMediaRecorder.getSurface()拿不到Surface对象this.mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenRecorder",width, height,displayMetrics.densityDpi,DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,mMediaRecorder.getSurface(), null, null);mediaRecorderStars();}/*** 截图*/public void startCapture() {String mImageName = System.currentTimeMillis() + ".png";Log.i(TAG, "image name is : " + mImageName);Image image = mImageReader.acquireLatestImage();if (image == null) {Log.e(TAG, "image is null.");if (screenshotRecordCallback != null) {screenshotRecordCallback.onScreenshotFailure();}return;}int width = image.getWidth();int height = image.getHeight();final Image.Plane[] planes = image.getPlanes();final ByteBuffer buffer = planes[0].getBuffer();int pixelStride = planes[0].getPixelStride();int rowStride = planes[0].getRowStride();int rowPadding = rowStride - pixelStride * width;Bitmap mBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);mBitmap.copyPixelsFromBuffer(buffer);mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, width, height);image.close();if (mBitmap != null) {// 保存或者显示...if (screenshotRecordCallback != null) {screenshotRecordCallback.onScreenshotSuccess(null, mBitmap);}}}/*** 录屏*/private void initMediaRecorder(File file, int width, int height) {this.mMediaRecorder = new MediaRecorder();// 设置音频来源 需要动态申请 android.permission.RECORD_AUDIO 权限this.mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置视频来源this.mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);// 设置输出格式this.mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);// 设置输出文件this.mVideoPath = file.getAbsolutePath();this.mMediaRecorder.setOutputFile(mVideoPath);// 设置视频宽高this.mMediaRecorder.setVideoSize(width, height);// 设置视频帧率this.mMediaRecorder.setVideoFrameRate(30);// 设置视频编码比特率this.mMediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);// 设置音频编码this.mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);// 设置视频编码this.mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);try {this.mMediaRecorder.prepare();} catch (IOException e) {e.printStackTrace();}}//通过mVideoPath地址确定是否在录屏public boolean isRecording() {Log.e(TAG, "mVideoPath is " + mVideoPath + ",b:" + StringUtils.isEmpty(mVideoPath));return !StringUtils.isEmpty(mVideoPath);}//开始录制public void mediaRecorderStars() {if (StringUtils.isEmpty(mVideoPath)) {Log.e(TAG, "mVideoPath is null");return;}if (mMediaRecorder == null) {Log.e(TAG, "mMediaRecorder is null");return;}mMediaRecorder.start();if (screenshotRecordCallback != null) {screenshotRecordCallback.onRecordStart();}}//结束录制public void mediaRecorderStop() {if (mMediaRecorder != null) {mMediaRecorder.stop();if (screenshotRecordCallback != null) {screenshotRecordCallback.onRecordStop(mVideoPath);}mVideoPath = null;mMediaRecorder.reset();} else {Log.e(TAG, "mMediaRecorder is null");}}/*** 释放相关资源*/public void release() {if (mImageReader != null) {mImageReader.close();}if (mMediaRecorder != null) {mMediaRecorder.setOnErrorListener(null);mMediaProjection.stop();mMediaRecorder.reset();mMediaRecorder.release();}if (mVirtualDisplay != null) {mVirtualDisplay.release();mVirtualDisplay = null;}if (mMediaProjection != null) {mMediaProjection.stop();mMediaProjection = null;}}public interface ScreenshotRecordCallback {void onScreenshotSuccess(String path, Bitmap bitmap);void onScreenshotFailure();void onRecordStart();void onRecordStop(String path);}

为了向别人、向世界证明自己而努力拼搏,而一旦你真的取得了成绩,才会明白:人无须向别人证明什么,只要你能超越自己。


http://www.ppmy.cn/news/280998.html

相关文章

什么是好的录屏软件?5 款值得收藏的屏幕录制软件

Windows 有大量的屏幕录制工具。其中一些是免费的&#xff0c;一些需要付费&#xff0c;还有一些与您可能已经安装的其他软件捆绑在一起。 有几种不同类型的可用解决方案&#xff1a; 截屏软件旨在录制您的屏幕&#xff0c;以便您创建视频教程或演示文稿。这些应用程序通常包括…

免费屏幕录像软件哪个好?简单几步教你快速录制无水印的高清视频!

不论是做自媒体的视频&#xff08;比如游戏解说&#xff0c;游戏经验分享&#xff09;&#xff0c;还是录制微课、网络直播视频等等需求&#xff0c;大家对录制视频的需求越来越大了。那么&#xff0c;想要快速录制一个没有水印的高清视频&#xff0c;到底怎么具体操作&#xf…

屏幕录像专家

默认录制的是exe格式&#xff0c;转为avi清晰度不够&#xff0c;此时根据软件弹出的提示&#xff0c;下载mpeg4解码器&#xff1a;www.tlxsoft.com/mpeg4.htm 安装解码器后&#xff0c;选择mpeg4进行转换avi&#xff0c;就清晰了&#xff1b;

Win10怎么录制高清的电脑屏幕?Win10屏幕录制工具哪个好?

Win10怎么录制高清的电脑屏幕&#xff1f;Win10屏幕录制工具哪个好&#xff1f; 看到很多小伙伴在网上问怎么在Win10上录制电脑屏幕&#xff0c;有什么好用的工具&#xff1f; 现在确实录屏的需求很大&#xff0c;我自己就在电脑上录制过游戏视频、在线网课和桌面屏幕等等视频…

100天精通Golang(基础入门篇)——第4天: Go语言中的变量与常量详解:声明、赋值和使用

&#x1f337; 博主 libin9iOak带您 Go to Golang Language.✨ &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &#x1f30a; 《I…

录屏软件哪个好?五款免费视频录屏软件

现如今在日常生活中都可以使用得上录屏软件&#xff0c;比如线上会议直播、线上教程课程、网课直播、玩游戏精彩瞬间等等&#xff1b;在互联网众多推荐下&#xff0c;到底录屏软件哪个好&#xff1f;今天小编在这里给大家分享五款免费视频录屏软件&#xff0c;有需要的朋友可以…

录屏大师电脑版推荐(一键录制声画同步的视频)

很多小伙伴使用电脑多年&#xff0c;却不知道电脑有录屏功能。想要对电脑屏幕进行录制&#xff0c;只需在电脑上安装一个录屏大师。那有没有录屏大师电脑版推荐呢&#xff1f; 在试用了多款电脑录屏大师之后&#xff0c;小编今天给大家推荐一款可以一键录制声画同步视频的录屏大…

录屏软件电脑版哪个好?4个电脑免费录屏软件推荐

在我们生活中&#xff0c;有很多需要录制视频的地方&#xff0c;所以我们经常需要录制视频。那么&#xff0c;电脑免费录屏软件哪个好&#xff1f;软件有很多&#xff0c;这是很多朋友都在问的问题。 现在市面上可以说是鱼龙混杂&#xff0c;但是有些软件是真的好用&#xff0…