/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. */ privatevoidopenCamera(int width, int height){ if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) { requestVideoPermissions(); return; } final Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } //获取CameraManager对象 CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.d(TAG, "tryAcquire"); //做打开超时判断,超过2.5秒则抛出异常,对应release()结束 if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { thrownew RuntimeException("Time out waiting to lock camera opening."); } String cameraId = manager.getCameraIdList()[0];//获取后摄id
// Choose the sizes for camera preview and video recording CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); //类似之前的Parameters StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); //选择录像尺寸 mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); //选择合适的预览尺寸 mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);
int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } configureTransform(width, height); mMediaRecorder = new MediaRecorder(); //打开Camera,通过CameraDevice.StateCallback回调打开结果 manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show(); activity.finish(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)) .show(getChildFragmentManager(), FRAGMENT_DIALOG); } catch (InterruptedException e) { thrownew RuntimeException("Interrupted while trying to lock camera opening."); } }
/** * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its status. */ private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
// Set up Surface for the camera preview Surface previewSurface = new Surface(texture); surfaces.add(previewSurface); mPreviewBuilder.addTarget(previewSurface);
// Set up Surface for the MediaRecorder mRecorderSurface = mMediaRecorder.getSurface();//获取MediaRecorder预览输出载体 surfaces.add(mRecorderSurface); mPreviewBuilder.addTarget(mRecorderSurface);
// Start a capture session // Once the session starts, we can update the UI and start recording mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {