Android开发之在软件内录屏录画面,直接CV就能用

关于Android开发录屏的资料,真的是很难找到那种拿来就能用的,不是付费专栏就是要积分才能下载源码,起不到任何帮助。我需要的是录制软件画面,找到的几个例子都是录制时返回桌面,然后弹出小窗口开始录制桌面,而且源码内容都太多了很难get到录屏重点。没办法最后只好去GitHub找找有没有简单点的源码,可算是找到一个简单易用的,随机改改就能实现需求,这里整理下分享给大家,希望看了可以少走弯路。

public class MainActivity extends AppCompatActivity {
    
    

    private static final String TAG = "MainActivity";
    private static final int PERMISSION_CODE = 1;
    private int mScreenDensity;
    private MediaProjectionManager mProjectionManager;
    private static final int DISPLAY_WIDTH = 480;
    private static final int DISPLAY_HEIGHT = 640;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaProjectionCallback mMediaProjectionCallback;
    private MediaRecorder mMediaRecorder;
    private Button btnRecord,btnReady;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;

        initRecorder();
        prepareRecorder();

        mProjectionManager = (MediaProjectionManager) getSystemService
                (Context.MEDIA_PROJECTION_SERVICE);

        btnReady = findViewById(R.id.btnReady);
        btnReady.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                shareScreen();//会打开新页面
                btnReady.setText("录制准备就绪");
            }
        });
		btnRecord = findViewById(R.id.btnRecord);
        btnRecord.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                if(btnRecord.getText().equals("开始录制")) {
    
    
                    btnRecord.setText("停止录制");

                    if (mVirtualDisplay == null) {
    
    
                        mVirtualDisplay = createVirtualDisplay();
                    }
                    mMediaRecorder.start();
                }
                else{
    
    
                    btnRecord.setText("开始录制");
                    mMediaRecorder.stop();
                    mMediaRecorder.reset();
                }
            }
        });
        mMediaProjectionCallback = new MediaProjectionCallback();
    }

    @Override
    public void onDestroy() {
    
    
        super.onDestroy();
        if (mMediaProjection != null) {
    
    
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
        if (requestCode != PERMISSION_CODE) {
    
    
            Log.e(TAG, "Unknown request code: " + requestCode);
            return;
        }
        if (resultCode != RESULT_OK) {
    
    
            Toast.makeText(this,
                    "Screen Cast Permission Denied", Toast.LENGTH_SHORT).show();
            return;
        }
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
        mMediaProjection.registerCallback(mMediaProjectionCallback, null);
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
    }

    private void shareScreen() {
    
    
        if (mMediaProjection == null) {
    
    
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), PERMISSION_CODE);
            return;
        }
    }

    private void stopScreenSharing() {
    
    
        if (mVirtualDisplay == null) {
    
    
            return;
        }
        mVirtualDisplay.release();
        //mMediaRecorder.release();
    }

    private VirtualDisplay createVirtualDisplay() {
    
    
        return mMediaProjection.createVirtualDisplay("MainActivity",
                DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
    }

    private class MediaProjectionCallback extends MediaProjection.Callback {
    
    
        @Override
        public void onStop() {
    
    
            if (btnRecord.getText().equals("停止录制")) {
    
    
                mMediaRecorder.stop();
                mMediaRecorder.reset();
                Log.v(TAG, "Recording Stopped");
            }
            mMediaProjection = null;
            stopScreenSharing();
            Log.i(TAG, "MediaProjection Stopped");
        }
    }

    private void prepareRecorder() {
    
    
        try {
    
    
            mMediaRecorder.prepare();
        } catch (IllegalStateException | IOException e) {
    
    
            e.printStackTrace();
            finish();
        }
    }

    public String getFilePath() {
    
    
        final String directory = Environment.getExternalStorageDirectory() + File.separator + "Recordings";
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    
    
            Toast.makeText(this, "Failed to get External Storage", Toast.LENGTH_SHORT).show();
            return null;
        }
        final File folder = new File(directory);
        boolean success = true;
        if (!folder.exists()) {
    
    
            success = folder.mkdir();
        }
        String filePath;
        if (success) {
    
    
            String videoName = ("capture_" + getCurSysDate() + ".mp4");
            filePath = directory + File.separator + videoName;
        } else {
    
    
            Toast.makeText(this, "Failed to create Recordings directory", Toast.LENGTH_SHORT).show();
            return null;
        }
        return filePath;
    }

    public String getCurSysDate() {
    
    
        return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
    }

    private void initRecorder() {
    
    
        if (mMediaRecorder == null) {
    
    
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(10 * 1024 * 1024);
            mMediaRecorder.setVideoFrameRate(60);
            mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
            mMediaRecorder.setOutputFile(getFilePath());
        }
    }
}

只需要自己做两个按钮,就可以完成录制功能了。之所以需要两个按钮是因为准备录制时会重新打开页面,屏幕可能会顿一下或者闪一下,如果准备后直接录制,会把屏幕闪一下的画面也录下,所以这里放两个按钮,准备好了再录制,确保能录到自己想要的画面。

おすすめ

転載: blog.csdn.net/qq_35761934/article/details/121608284