how to switch between front and back camera when using MediaRecorder android

不打扰是莪最后的温柔 提交于 2019-11-29 00:24:47

I have something that might also help, in order to jump to the other camera, follow this method:

public void flipit() {
    //myCamera is the Camera object
    if (Camera.getNumberOfCameras()>=2) {
        myCamera.stopPreview();
        myCamera.release();
        //"which" is just an integer flag
        switch (which) {
        case 0:
            myCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
            which = 1;
            break;
        case 1:
            myCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            which = 0;
            break;
        }
        try {
            myCamera.setPreviewDisplay(mHolder);
            //"this" is a SurfaceView which implements SurfaceHolder.Callback,
            //as found in the code examples
            myCamera.setPreviewCallback(this);
            myCamera.startPreview();
        } catch (IOException exception) {
            myCamera.release();
            myCamera = null;
        }
    }
}

Now... for the magic trick, don't call this method from the main thread. Instead this method has to be kicked off from a separate thread, my code does this:

        //btn is a Button that the user clicks on
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //onClick is invoked from main thread
            //kick-off a different Thread to handle this call
            Thread t = new Thread() {
                public void run() {
                    //myViewer is the SurfaceView object which uses
                    //the camera
                    myViewer.flipit();
                }
            };
            t.start();
        }
    });

I've tested this on Android 4.1.1 so I think it might work for you. (or until Google decides to break the way the camera opening/closing/releasing/unlocking/reconnecting/surfaceholder/onPause/onResume/etc..? works)

First, check if your device has more than one camera:

    Camera.getNumberOfCameras();

Then, assign a camId value:

    camId = Camera.CameraInfo.CAMERA_FACING_BACK;

or

    camId = Camera.CameraInfo.CAMERA_FACING_FRONT;

and then creates a new Camera object to access a particular hardware camera (camId).

    mCamera = Camera.open(camId);

Hope this help!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!