Android Camera video demo, androidcamera

Source: Internet
Author: User

Android Camera video demo, androidcamera
Google launched the Camera2 class in Android 5.0 to replace Camera. However, Camera2 requires the minimum android sdk version to be minSdkVersion = 21 (5.0 system), so Camera2 cannot completely replace Camera, when it is compatible with earlier versions, the two must be jointly developed. The following is an example of Camera shooting: First, you need to layout A SurfaceView in xml to set full screen

<SurfaceViewandroid:id="@+id/surfaceView"android:layout_width="match_parent"android:layout_height="match_parent"/>

 

The status bar and titleBar are also hidden:
RequestWindowFeature (Window. FEATURE_NO_TITLE); // remove the title bar getWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN, WindowManager. LayoutParams. FLAG_FULLSCREEN); // set full screen.

 

Obtain the SurfacView instance and its owner SurfaceHolder, and access the SurfaceHolder. Callback,
MSurfaceView = (SurfaceView) findViewById (R. id. surfaceView); mSurfaceHolder = mSurfaceView. getHolder (); // get holdermSurfaceHolder. addCallback (this); // Add the holder to the callback interface mSurfaceHolder. setKeepScreenOn (true );

 

SurfaceHolder. Callback will be called after the Actvity Initialization is complete on the page, then initialize Camera in the Callback surfaceChanged, that is, open the preview page:
@ Overridepublic void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {if (mCamera! = Null) {freeCameraResource ();} try {mCamera = Camera. open (); if (mCamera = null) return; mCamera. setDisplayOrientation (90); mCamera. setPreviewDisplay (mSurfaceHolder); parameters = mCamera. getParameters (); // obtain the Camera Parameter List <Camera. size> mSupportedPreviewSizes = parameters. getSupportedPreviewSizes (); List <Camera. size> mSupportedVideoSizes = parameters. getSupportedVideoSizes (); optimalSize = CameraHelper. getOptimalVideoSize (mSupportedVideoSizes, mSupportedPreviewSizes, height, width); parameters. setPreviewSize (optimalSize. width, optimalSize. height); // sets the preview image size parameters. set ("orientation", "portrait"); List <String> focusModes = parameters. getSupportedFocusModes (); if (focusModes. contains ("continuous-video") {parameters. setFocusMode (Camera. parameters. FOCUS_MODE_CONTINUOUS_VIDEO);} mFpsRange = parameters. getSupportedPreviewFpsRange (); mCamera. setParameters (parameters); // sets the Camera Parameter mCamera. startPreview (); // start preview} catch (Exception io) {io. printStackTrace ();}}

 

This method returns the width and height of SurfaceView. Based on the given size and width ratio, obtain a preview size that is best suited to each other. You can see the following two parameters:
 List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes();

 

The two queues are the preview size supported by the camera (generally the size of the photo when taking the photo), and the other one is the size that supports adaptation, because they are queues, indicating that the camera supports many sets of sizes, in addition, the size of the photo is different from that of the video. I checked several mobile phones in debug mode. Generally, the camera supports a smaller size and more photos. In this way, we need to obtain the best matching preview size through the width and height given in the previous method:
public static Camera.Size getOptimalVideoSize(List<Camera.Size> supportedVideoSizes,List<Camera.Size> previewSizes, int w, int h) {// Use a very small tolerance because we want an exact match.final double ASPECT_TOLERANCE = 0.1;double targetRatio = (double) w / h; // Supported video sizes list might be null, it means that we are allowed to use the preview// sizesList<Camera.Size> videoSizes;if (supportedVideoSizes != null) {videoSizes = supportedVideoSizes;} else {videoSizes = previewSizes;}Camera.Size optimalSize = null; // Start with max value and refine as we iterate over available video sizes. This is the// minimum difference between view and camera height.double minDiff = Double.MAX_VALUE; // Target view heightint targetHeight = h; // Try to find a video size that matches aspect ratio and the target view size.// Iterate over all available sizes and pick the largest size that can fit in the view and// still maintain the aspect ratio.for (Camera.Size size : videoSizes) {double ratio = (double) size.width / size.height;if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)continue;if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {optimalSize = size;minDiff = Math.abs(size.height - targetHeight);}} // Cannot find video size that matches the aspect ratio, ignore the requirementif (optimalSize == null) {minDiff = Double.MAX_VALUE;for (Camera.Size size : videoSizes) {if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {optimalSize = size;minDiff = Math.abs(size.height - targetHeight);}}}return optimalSize;}
This method is used to obtain the best preview and camera size. Then set the preview image size:
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
You can obtain the parameter instance of the camera and set various effects, including the preview image, front camera, and flashlight.
Parameters = mCamera. getParameters (); // obtain the camera parameters

 

If you have set the camera parameters for preview, enable:
MCamera. setParameters (parameters); // set the camera parameter mCamera. startPreview (); // start previewing

 

Then a preview shooting page is displayed, which can also be used for photography. To take a video, you also need to instantiate MediaRecorder, then pass in camera and initialize the corresponding parameters:
MMediaRecorder. setCamera (mCamera); mMediaRecorder. setOnErrorListener (this); mMediaRecorder. setAudioSource (MediaRecorder. audioSource. DEFAULT); mMediaRecorder. setVideoSource (MediaRecorder. videoSource. CAMERA); // video source // Use the same size for recording profile. camcorderProfile mProfile = CamcorderProfile. get (CamcorderProfile. QUALITY_HIGH); mProfile. videoFrameWidth = optimalSize. width; mProfile. videoFrameHeight = optimalSize. height; mMediaRecorder. setProfile (mProfile); // This setting is used to extract certain frames of a video. Do not set this parameter when you are recording a video. // mMediaRecorder. setCaptureRate (mFpsRange. get (0) [0]); // obtain the minimum number of frames recorded per second (mMediaRecorder. setOutputFile (mVecordFile. getAbsolutePath (); mMediaRecorder. prepare (); mMediaRecorder. start ();
It is stopped at the time of recording, and must be reset before it can be used again.
try {mMediaRecorder.stop();mMediaRecorder.reset();} catch (Exception e) {e.printStackTrace();} 

 

Remember to release destroy on the page:
 private void releaseRecord() {if (mMediaRecorder != null) {mMediaRecorder.setPreviewDisplay(null);mMediaRecorder.setOnErrorListener(null);try {mMediaRecorder.release();} catch (IllegalStateException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}mMediaRecorder = null;}

 

Flashlight off and on:
private void flashLightToggle(){try {if(isFlashLightOn){parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);mCamera.setParameters(parameters);isFlashLightOn = false;}else {parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);mCamera.setParameters(parameters);isFlashLightOn = true;}} catch (Exception e) {e.printStackTrace();}}

 

To switch between the front and back cameras, you need to re-initialize the camera instance:
Private void switchCamera () {Camera. cameraInfo cameraInfo = new Camera. cameraInfo (); int cameraCount = Camera. getNumberOfCameras (); // obtain the number of cameras for (int I = 0; I <cameraCount; I ++) {Camera. getCameraInfo (I, cameraInfo); // obtain the information of each camera if (cameraPosition = 1) {// change it to front if (cameraInfo. facing = Camera. cameraInfo. CAMERA_FACING_FRONT) {// specifies the camera orientation, and CAMERA_FACING_FRONT front CAMERA_FACING_BACK and rear mCamera. stopPreview (); // stop the previous camera preview mCamera. release (); // release the resource mCamera = null; // cancel the original Camera mCamera = Camera. open (I); // open the currently selected camera try {mCamera. setDisplayOrientation (90); mCamera. setPreviewDisplay (mSurfaceHolder); // display the screenshot using surfaceview} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} mCamera. setParameters (parameters); // sets the Camera Parameter mCamera. startPreview (); // start previewing cameraPosition = 0; break;} else {// now is the front end, change to the rear if (cameraInfo. facing = Camera. cameraInfo. CAMERA_FACING_BACK) {// specifies the camera orientation, and CAMERA_FACING_FRONT front CAMERA_FACING_BACK and rear mCamera. stopPreview (); // stop the previous camera preview mCamera. release (); // release the resource mCamera = null; // cancel the original Camera mCamera = Camera. open (I); // open the currently selected camera try {mCamera. setDisplayOrientation (90); mCamera. setPreviewDisplay (mSurfaceHolder); // display the screenshot using surfaceview} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} mCamera. setParameters (parameters); // sets the Camera Parameter mCamera. startPreview (); // start previewing cameraPosition = 1; break ;}}}}

 

Recording page: This is the main step to use camera to camera, demo: https://github.com/xiaoxiaoqingyi/android-CameraVideo If You Want To Know Camera2, you can also look at the official example of google Camera2: https://github.com/googlesamples/android-Camera2Basic

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.