Android屏幕录制

一、申请权限

<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" />
public static void checkPermission(AppCompatActivity activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission =
                    ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                //动态申请
                ActivityCompat.requestPermissions(activity, new String[]{
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
                return;
            } else {
                return;
            }
        }
        return;
    }
    

二、适配Android Q

开始之前首先适配Android Q,对于Android Q,直接startService会抛出如下异常,因此,首先得适配AndroidQ:

Media projections require a foreground service of type ServiceInfo.FOREGROUN

1、配置前台服务权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

2、添加服务节点

        <service
            android:name=".server.RecordService" //RecordService为录音的服务。
            android:enabled="true"
            android:exported="true"
            tools:targetApi="q"
            android:foregroundServiceType="mediaProjection" />

3、启动服务

context.startForegroundService(intent);

4、配置通知栏

        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("正在录制屏幕内容...")
                .setSmallIcon(R.mipmap.ic_launcher);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(appId, getResources().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId(appId);
        }
        startForeground(1, builder.build());

三、获取用户录制屏幕授权

MediaProjectionManager , MediaProjectionManager 是系统提供的一种服务,当我们拿到这个服务对象,可以创建一个 Intent ,通过这个 Intent 可以启动一个弹框样式的 Activity,如果用户授权了,那我们便可以继续下一步屏幕录制。

    public void start(){
        projectionManager = (MediaProjectionManager) activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = projectionManager.createScreenCaptureIntent();
        activity.startActivityForResult(captureIntent,REQUEST_SYSTEM_RECORD_SCREEN);
    }

四、在 onActivityResult 对用户的授权做处理

    public static void onActivityResult(Context context, Intent data) {
        
        if (data != null) {
            Intent intent = new Intent(context, MediaRecordService.class);
            intent.putExtra("code", Activity.RESULT_OK);
            intent.putExtra("data", data);
            intent.putExtra("path", path);
            intent.putExtra("width", width);
            intent.putExtra("height", height);
            intent.putExtra("bit", bit);
            intent.putExtra("fps", fps);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
            context.bindService(intent, new RecordServiceConn(), Context.BIND_AUTO_CREATE);
        }
    }

五、创建RecordService服务,开启录音

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("正在录制屏幕内容...")
                .setSmallIcon(R.mipmap.ic_launcher);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(appId(), getResources().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId(appId);
        }
        startForeground(1, builder.build());

        if (intent != null) {
            outPath = intent.getStringExtra("path");
            width = intent.getIntExtra("width", 720);
            height = intent.getIntExtra("height", 1080);
            bit = intent.getIntExtra("bit", 1000);
            fps = intent.getIntExtra("fps", 24);
            int code = intent.getIntExtra("code", -1);
            Intent data = intent.getParcelableExtra("data");
            mediaProjection = createMediaProjection(code, data);
            mediaRecorder = createMediaRecorder();
            // 必须在mediaRecorder.prepare() 之后调用,否则报错"fail to get surface"
            virtualDisplay = createVirtualDisplay();
            mediaRecorder.start();
        }
        return Service.START_NOT_STICKY;
    }
    private MediaRecorder createMediaRecorder() {
        MediaRecorder mediaRecorder = new MediaRecorder();
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mediaRecorder.setOutputFile(outPath);
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mediaRecorder.setVideoSize(width, height);
        mediaRecorder.setVideoFrameRate(fps);
        mediaRecorder.setVideoEncodingBitRate(bit);
        try {
            mediaRecorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mediaRecorder;
    }

    private MediaProjection createMediaProjection(int resultCode, Intent intent) {
        return ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)).getMediaProjection(resultCode, intent);
    }

    private VirtualDisplay createVirtualDisplay() {
        ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
        imageReader.setOnImageAvailableListener(imageAvailableListener, null);
        return mediaProjection.createVirtualDisplay(TAG, width, height, densityDpi(), DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
    }

setVideoSize设置的宽高数值必须要和摄像头支持的数值相匹配,否则报错"fail to get surface",另外上面会存在多个地方设置width、height,如果设置的不一样,图像会错位,和录制的原始画面不一致。

六、获取录制视频帧

在createVirtualDisplay方法中有设置setOnImageAvailableListener,这里可以监听视频帧,获取bitmap,如果需要的话:

    ImageReader.OnImageAvailableListener imageAvailableListener = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            Image image = reader.acquireLatestImage();
            if (image != null) {
                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);
                image.close();
            }
        }
    };

七、结束录制

    public void stop() {
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            release();
            stopForeground(true);
            stopSelf();
        }
    }
    public void release() {
        if (virtualDisplay != null) {
            virtualDisplay.release();
            virtualDisplay = null;
        }
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);
            mediaProjection.stop();
            mediaRecorder.reset();
            mediaRecorder.release();
        }
        if (mediaProjection != null) {
            mediaProjection.stop();
            mediaProjection = null;
        }
    }

录制视频结束时候一定要 mediaRecorder.stop();如果直接退出APP或者杀死进程,录制的视频则无法播放。

 

 

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值