About using Android new camera namely CAMERA2 use introduction and solve Camera.previewcallback and Mediarecorder cannot simultaneously

Source: Internet
Author: User

The new camera API, also known as CAMERA2, was introduced in Android 5.0. In general, we use the old Android camera API, even though in Android studio always hints are obsolete, but as long as it is available, there is no need to write two sets of code separately in order to use the new API. Then why do you introduce the use of CAMERA2? The root of all the problems is the demand for diversification, especially in the Android field, where compatibility issues are endless. Often encounter, other mobile phones are OK, how can this not ...

I was like everyone else, and I ran into a camera-related compatibility issue. In addition to the detection of each frame, our app uses the old camera API to perform the current live-detection video recording while living in vivo recognition. Under the diversified model test, we found that under the red Rice Note2 and Meizu MX5, can not be normal simultaneous live detection and video recording, in exchange for a more technical point is that, in the old API, Camera.previewcallback and Mediarecorder cannot be carried out simultaneously. What to do? Google to wave Search, you will find, and then egg ... At first, we also specifically contacted the Meizu camera developers, thought there would be something more "Meizu" scheme, the result they directly back to a sentence: platform-related, MX5 does not support video output while providing preview data. What to do? Cut demand? This critical process has been specifically reviewed by the legal department, which can be said to be cut. Whether we can cut off this requirement while still studying how to solve the problem

We found that these two can not be carried out at the same time mobile phones are more than 5.0, so I think, perhaps the new Camera2 may be resolved by the ~ below began to carry out professional technical dry explanation mode ...

When we want to learn to use a new API, it is best to go directly to the official website to find reference, and then try to scientific Internet. Most of Android's API examples, all in Https://github.com/googlesamples, this mention of the use of CAMERA2, of course, is also downloaded from there, the source address is as follows:

Https://github.com/googlesamples/android-Camera2Basic and Https://github.com/googlesamples/android-Camera2Video. But the code inside the googlesamples is more primitive.

We need to calm down to analyze the process of camera use:

1, first of all must judge the authority, whether there is the right to use the camera;

2, by what means to connect the camera equipment;

3, how to get the camera equipment after the video;

4, how to listen to each frame of data in the process of recording;

  

First, on the inspection authority does not say, here add a sentence there is a class called Activitycompat, if you have not used before can look, is the class under the V4 package.

Two, Camera2 the way to open the camera device is not the same as the old, before the new one directly on the open, more direct. Now treat the camera as a service, apply it, and apply it in the following way,

private void Opencamera () {if (isopened) {return;        } isopened = true;        Cameramanager manager = (Cameramanager) getsystemservice (Context.camera_service); try {String cameraid = manager.getcameraidlist () [0];//This may be a lot, but it is usually two, the first is the back, the second is the predecessor; Camerachara            Cteristics characteristics = manager.getcameracharacteristics (cameraid);            Streamconfigurationmap map = Characteristics.get (CAMERACHARACTERISTICS.SCALER_STREAM_CONFIGURATION_MAP);            Assert map! = NULL;            Imagedimension = map.getoutputsizes (Surfacetexture.class) [0]; Manager.opencamera (Cameraid, New Cameradevice.statecallback () {@Override public void OnOpen                    Ed (cameradevice camera) {G.I ("onopened");                Createcamerapreview (camera); } @Override public void ondisconnected (Cameradevice camera) {G.I ("Ondisc OnnectEd ");                Camera.close (); } @Override public void OnError (Cameradevice camera, int. error) {G.E ("on                    Error, "+ Error");                Camera.close (); }}, Handlerhelper.getbackgroundhandler ());//This specifies its background to run, if the direct UI thread can also, directly fill null; G.I ("Open Camera" + cam        Eraid);        } catch (Cameraaccessexception e) {e.printstacktrace (); }    }

Third, the callback to get the camera device is like the code of public void onopened (Cameradevice camera) method, at this time the Cameradevice is we can fully use the camera. Once you get the camera, start creating previews as preview.

protected voidCreatecamerapreview (FinalCameradevice Cameradevice) {        Try {            if(NULL==Cameradevice) {G.I ("Updatepreview Error, return"); return;            } setupimagereader ();            Setupmediarecorder (); FinalCapturerequest.builder Capturerequestbuilder =cameradevice.createcapturerequest (Cameradevice.template_record); Surfacetexture Texture=textureview.getsurfacetexture ();            Texture.setdefaultbuffersize (Imagedimension.getwidth (), Imagedimension.getheight ()); Surface Texturesurface=NewSurface (texture); Surface Recordersurface=Mmediarecorder.getsurface (); Surface Imagesurface=Imagereader.getsurface ();            Capturerequestbuilder.addtarget (Texturesurface);            Capturerequestbuilder.addtarget (Recordersurface);            Capturerequestbuilder.addtarget (Imagesurface); List<Surface> surfacelist =arrays.aslist (Texturesurface, Recordersurface, imagesurface); Cameradevice.createcapturesession (Surfacelist,NewCameracapturesession.statecallback () {//configure surface to accept images @Override Public voidonconfigured (cameracapturesession cameracapturesession) {Capturerequestbuilder.set (CaptureRequest .                    Control_mode, Camerametadata.control_mode_auto); Try{cameracapturesession.setrepeatingrequest (Capturerequestbuilder.build (),NULL, Handlerhelper.getbackgroundhandler ());//After a successful configuration, the camera image is started listening}Catch(cameraaccessexception e) {e.printstacktrace ();                } mmediarecorder.start (); } @Override Public voidonconfigurefailed (cameracapturesession cameracapturesession) {toastutils.show ("Configuration Change");        }}, Handlerhelper.getbackgroundhandler ()); } Catch(cameraaccessexception e) {e.printstacktrace (); }    }    Private voidSetupmediarecorder () {Mmediarecorder=NewMediarecorder ();        Mmediarecorder.setaudiosource (MediaRecorder.AudioSource.DEFAULT);        Mmediarecorder.setvideosource (MediaRecorder.VideoSource.SURFACE);        Mmediarecorder.setprofile (Getcamcorderprofile ()); Mmediarecorder.setoutputfile (NewFile (Getexternalcachedir (), System.currenttimemillis () + ". mp4"). GetAbsolutePath ()); Try{mmediarecorder.prepare (); } Catch(IOException e) {e.printstacktrace (); }    }    Private voidSetupimagereader () {ImageReader= Imagereader.newinstance (Imagedimension.getwidth (), Imagedimension.getheight (), imageformat.yuv_420_888, 10); Imagereader.setonimageavailablelistener (NewImagereader.onimageavailablelistener () {@Override Public voidonimageavailable (ImageReader reader) {image Image=Reader.acquirelatestimage (); if(Image! =NULL) {image.close (); } G.I ("Onimageavailable");    }}, Handlerhelper.getbackgroundhandler ()); }

Because the CAMERA2 API is used in a way that the camera device can output images to multiple surface. As above code, through Cameradevice.createcapturesession (...) method to configure the surface to be output, any surface that has not been configured will have an error when used. At the same time there is a callback notification, whether the configuration is successful, you can start to start the output of the image monitoring, that is, Cameracapturesession.setrepeatingrequest (Capturerequestbuilder.build (), NULL , Handlerhelper.getbackgroundhandler ()), where Capturerequestbuilder is to configure camera properties and add those that have been successfully configured for surface, and how to receive images of the camera, The owners of each surface are defined by themselves. Here is the use of Mediarecorder and ImageReader, one for the video, one for the so-called monitoring previewcallback.

Note: When using ImageReader, the card is compared, especially if the JPEG format is used, since the use of Jpeg,imagereader requires additional processing. I used the imageformat.yuv_420_888 format in order to make the callback the same as the old Previewcallback. This format, the output is very smooth.

  

About using Android new camera namely CAMERA2 use introduction and solve Camera.previewcallback and Mediarecorder cannot simultaneously

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.