1

我的 Video Recoding 应用程序录制视频,它正在从后置摄像头工作,现在我也想使用前置摄像头录制视频。所以用户可以在相机之间切换。用户可以选择要使用哪个摄像机录制视频。最初,当我的活动加载后摄像头打开并开始预览时,但是当我单击切换摄像头按钮时,它会给出异常java.lang.RuntimeException: Fail to connect to camera service。以下是我切换相机的代码:

private void initRecorder(Surface surface) throws IOException {

   try{
        if (mCamera != null) {
            mCamera.lock();
            mCamera.unlock();
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            mHolder.addCallback(null);
            mHolder = null;
        }

        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        if(cameraToOpen==1){
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);

        } else if(cameraToOpen==2){
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
        }

        mCamera.lock();
        mCamera.setDisplayOrientation(90); 
        mCamera.setPreviewDisplay(mHolder);
        mCamera.startPreview();
        mCamera.unlock();

    }catch(Exception e){

      }
 }

当用户单击切换相机按钮时,mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT); 会出现异常。如何使用两个相机。

编辑:

当我在活动开始时打开前置摄像头时,它工作正常。因此,只有在选择了初始相机时,我才能同时打开相机并从两者中记录。但是当我在相机之间切换时,它会出现无法连接到相机服务的异常。

4

1 回答 1

1

You can do the switch between cameras as stated below :

Button otherCamera = (Button) findViewById(R.id.OtherCamera);

otherCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (inPreview) {
    camera.stopPreview();
}

//NB: if you don't release the current camera before switching, you app will crash
camera.release();

//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
    currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
    currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);

setCameraDisplayOrientation(CameraActivity.this, currentCameraId, camera);
try {
    camera.setPreviewDisplay(previewHolder);
} catch (IOException e) {
    e.printStackTrace();
}
camera.startPreview();
}

For recording video while switching the camera you can follow more here switching between cameras using mediarecorder.

于 2019-03-12T08:45:12.687 回答