/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. */ privatevoidopenCamera(int width, int height) { if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) { requestVideoPermissions(); return; } finalActivityactivity= getActivity(); if (null == activity || activity.isFinishing()) { return; } //获取CameraManager对象 CameraManagermanager= (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.d(TAG, "tryAcquire"); //做打开超时判断,超过2.5秒则抛出异常,对应release()结束 if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { thrownewRuntimeException("Time out waiting to lock camera opening."); } StringcameraId= manager.getCameraIdList()[0];//获取后摄id
// Choose the sizes for camera preview and video recording CameraCharacteristicscharacteristics= manager.getCameraCharacteristics(cameraId); //类似之前的Parameters StreamConfigurationMapmap= 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);
intorientation= 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 = newMediaRecorder(); //打开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) { thrownewRuntimeException("Interrupted while trying to lock camera opening."); } }
/** * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its status. */ private CameraDevice.StateCallbackmStateCallback=newCameraDevice.StateCallback() {
// Set up Surface for the camera preview SurfacepreviewSurface=newSurface(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, newCameraCaptureSession.StateCallback() {