官方Android Camera2 录像示例--停止录像时崩溃修正

时间:2022-07-26 18:47:08

官方Android 使用Camera2示例项目地址:https://github.com/android/camera-samples

视频录像示例:https://github.com/android/camera-samples/tree/master/Camera2VideoJava

官方Android Camera2 录像示例--停止录像时崩溃修正

 

 官方Camera2VideoFragment.java停止录像代码,原来代码:会导致APP崩溃

    private void stopRecordingVideo() {
        // UI
        mIsRecordingVideo = false;
        mButtonVideo.setText(R.string.record);
        // Stop recording
        mMediaRecorder.stop();
        mMediaRecorder.reset();

        Activity activity = getActivity();
        if (null != activity) {
            Toast.makeText(activity, "Video saved: "   mNextVideoAbsolutePath,
                    Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Video saved: "   mNextVideoAbsolutePath);
        }
        mNextVideoAbsolutePath = null;
        startPreview();
    }

 

解决方法如下:

    private void stopRecordingVideo() {
        // UI
        mIsRecordingVideo = false;
        mButtonVideo.setText(R.string.record);
        //必须将这一句放置到MediaRecorder停止释放的前面,
        //否则就会造成,接收数据方(Encoder)已经停止了,而发送数据的session还在运行。才会造成以上错误。
 startPreview(); // Stop recording
        mMediaRecorder.stop();
        mMediaRecorder.reset();

        Activity activity = getActivity();
        if (null != activity) {
            Toast.makeText(activity, "Video saved: "   mNextVideoAbsolutePath,
                    Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Video saved: "   mNextVideoAbsolutePath);
        }
        mNextVideoAbsolutePath = null;
        
    }

另外修改closePreviewSession()方法,增加红色字体代码:

private void closePreviewSession() {
        if (mPreviewSession != null) {
            try { mPreviewSession.stopRepeating(); mPreviewSession.abortCaptures(); } catch (CameraAccessException e) { e.printStackTrace(); }
            mPreviewSession.close();
            mPreviewSession = null;
        }
    }

 

参考:https://blog.csdn.net/mengjiangyue/article/details/62435349