专栏首页Android NoteAndroid-录屏APP该怎么实现?

Android-录屏APP该怎么实现?

前言

这次不是需求了,这次是个人兴趣爱好。个人比较喜欢音视频方面的东西,还有就是有时候需要录屏去制作GIF图,所以就花时间去试着自己写一个简单的录屏小程序自用了。

经过一段时间的尝试,算是弄出来了一个能用的录屏小程序。

老规矩,先上图。

这里使用的是MediaProjectionManagerMediaProjectionVirtualDisplay,所以API级别最低支持到21。还有就是我的targetSdkVersion是22,这里我是偷懒了,避免了权限申请那一步。

public class ScreenRecorderActivity extends AppCompatActivity {

    public static final String TAG = "ez";
    private static final int DISPLAY_WIDTH = 720;
    private static final int DISPLAY_HEIGHT = 1280;
    private static final int RECORD_REQUEST_CODE = 100;
    private int mScreenDensity;
    private Button mBtnRecorder;
    boolean isRecording = false;
    private MediaRecorder mMediaRecorder;
    private VirtualDisplay mVirtualDisplay;
    private MediaProjection mMediaProjection;
    private MediaProjectionManager mProjectionManager;
    private MediaProjectionCallback mMediaProjectionCallback;
    private static final SparseIntArray ORIENTTIONS = new SparseIntArray();

    static {
        ORIENTTIONS.append(Surface.ROTATION_0, 90);
        ORIENTTIONS.append(Surface.ROTATION_90, 0);
        ORIENTTIONS.append(Surface.ROTATION_180, 270);
        ORIENTTIONS.append(Surface.ROTATION_270, 180);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_recorder_layout);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;

        mMediaRecorder = new MediaRecorder();
        mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);

        mBtnRecorder = (Button) findViewById(R.id.id_btn_screen_recorder);
        mBtnRecorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isStartRecordScreen();
            }
        });


    }
    //是否开启录制
    private void isStartRecordScreen() {
        if (!isRecording) {
            initRecorder();
            recordScreen();
        } else {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            stopRecordScreen();
        }
    }
    //初始化录制参数
    private void initRecorder() {
        try {
            if (mMediaRecorder == null) {
                Log.d(TAG, "initRecorder: MediaRecorder为空啊---");
                return;
            }
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 音频源
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);// 视频源
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//视频输出格式
            //这里的路径我是直接写死了。。。
            mMediaRecorder.setOutputFile("/storage/emulated/0/ScreenRecorder/" + System.currentTimeMillis() + ".mp4");//存储路径
            mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);// 设置分辨率
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);// 视频录制格式
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);// 音频格式
            mMediaRecorder.setVideoFrameRate(16);//帧率
            mMediaRecorder.setVideoEncodingBitRate(5242880);//视频清晰度
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            int orientataion = ORIENTTIONS.get(rotation + 90);
            mMediaRecorder.setOrientationHint(orientataion);//设置旋转方向
            mMediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //开始录制
    private void recordScreen() {
        if (mMediaProjection == null) {
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), RECORD_REQUEST_CODE);
            return;
        }

        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
        isRecording = true;
        changeText();
    }
    //停止录制
    private void stopRecordScreen() {
        if (mVirtualDisplay == null) {
            return;
        }

        mVirtualDisplay.release();
        destroyMediaProjection();
        isRecording = false;
        changeText();
    }
    //释放录制的资源
    private void destroyMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.unregisterCallback(mMediaProjectionCallback);
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }

    private VirtualDisplay createVirtualDisplay() {
        return mMediaProjection.createVirtualDisplay("ScreenRecorder", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
    }

    private void changeText() {
        if (isRecording) {
            mBtnRecorder.setText("停止录屏");
        } else {
            mBtnRecorder.setText("开始录屏");
        }
    }
    //录制回调
    private class MediaProjectionCallback extends MediaProjection.Callback {
        @Override
        public void onStop() {
            if (isRecording) {
                isRecording = false;
                changeText();
                mMediaRecorder.stop();
                mMediaRecorder.reset();
            }
            mMediaProjection = null;
            stopRecordScreen();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RECORD_REQUEST_CODE) {

            if (resultCode != RESULT_OK) {
                Toast.makeText(ScreenRecorderActivity.this, "录屏权限被禁止了啊", Toast.LENGTH_SHORT).show();
                isRecording = false;
                changeText();
                return;
            }

            mMediaProjectionCallback = new MediaProjectionCallback();
            mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
            mMediaProjection.registerCallback(mMediaProjectionCallback, null);
            mVirtualDisplay = createVirtualDisplay();
            mMediaRecorder.start();
            isRecording = true;
            changeText();
        }

    }
     //停止录制时,释放资源
    @Override
    protected void onStop() {
        super.onStop();
        destroyMediaProjection();
    }

    @Override
    public void onBackPressed() {
        if (isRecording) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("确定停止录屏吗?")
                    .setPositiveButton("停止", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mMediaRecorder.stop();
                            mMediaRecorder.reset();
                            stopRecordScreen();
                            finish();
                        }
                    }).setNegativeButton("继续录吧", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).create().show();

        } else {
            finish();

        }
    }
}

需要的权限:

    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

更多参数的设置请自行尝试,方法参数解释请点击这里

最后的最后,

祝大家元宵节快乐

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • RecycleView的拖动排序

    code_horse
  • Android-水平和垂直方向都可滑动的RecycleView

    code_horse
  • Android - ViewDragHelper实现京东、淘宝拖拽详情

    code_horse
  • NeurIPS 2019 马上要开了,如何为现场参会做准备?

    久负盛名的机器学习顶会 NeurIPS 2019 马上就要在加拿大温哥华开幕了。如今的 NeurIPS 除了参数人数众多之外,从 12 月 8 日一直到 12 ...

    AI科技评论
  • SAP Cloud for Customer的后台作业

    其实就是把SM37的功能用UI5做了一个前台界面给admin用: Click button Schedule:

    Jerry Wang
  • python大牛带你一节课掌握GUI编程并用PyQt5开发一个图形交互界面

    云飞
  • java程序员从小工到专家成神之路(2020版)

    java作为第一大编程语言,可谓源远流长,一代又一代的java程序员前仆后继走在java学习的路上。java程序员的学习之路在2020年又有什么变化呢?

    程序那些事
  • 异常中要了解的Throwable类中的几个方法

    *   public String getMessage()   获取异常的信息,返回的是字符串

    黑泽君
  • leetcode-225-Implement Stack using Queues

    Implement the following operations of a stack using queues.

    chenjx85
  • Java架构师学习路线

    java架构师,首先要是一个高级java攻城狮,熟练使用各种框架,并知道它们实现的原理。jvm虚拟机原理、调优,懂得jvm能让你写出性能更好的代码;池技术,什么...

    Java后端工程师

扫码关注云+社区

领取腾讯云代金券