Android calls phone camera using Mediarecorder video and play

Source: Internet
Author: User

Recently in the development of the project need to call the system camera video and playback.

Two issues were encountered in the development, recorded:

(1) In the development process, the camera occupies, failed to start, error. But I have closed the resources in Ondestory ().

Error Reason: Open the program, call the camera, press the home button to open the program call, error camera is occupied.

WORKAROUND: Close the resource in OnStop (), and in Onresume () to determine whether it is null, otherwise instantiate the resource.

(2) Where my video playback code is written in Fragment+viewpager, when switching back and forth fragment, the camera can only be called once, and where the fragment may be destroyed. (Here you can see the fragment life cycle call process)

Error reason: Viewpager has a cache loading mechanism that caches only the front and back pages of the current page. So in the process of switching back and forth, video playback fragment there is the possibility of continuous destruction, creation.

FIX: If your viewpager pages are not much, and you probably know its number of pages, you can modify the Viewpager cache page count.

Viewpagwer.setoffscreenpagelimit (int numbers); When the page is switched on, the numbers pages on both sides of the current page are not destroyed.

Here's a look at the specific code analysis:

Recording process:

Mediarecorder =NewMediarecorder ();//Create a Mediarecorder object//set the recording video source to cameraMediarecorder.setvideosource (MediaRecorder.VideoSource.CAMERA);//set the format of the video after recording is complete THREE_GPP to 3gp.mpeg_4 for MP4Mediarecorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP);//set the recorded video encoding h263 H264Mediarecorder.setvideoencoder (MediaRecorder.VideoEncoder.H264);//sets the resolution of the video recording. Must be placed behind the set encoding and format, otherwise the errorMediarecorder.setvideosize (176, 144); //sets the recorded video frame rate. Must be placed behind the set encoding and format, otherwise the errorMediarecorder.setvideoframerate (20); Mediarecorder.setpreviewdisplay (Surfaceview.getholder (). Getsurface ()); //set the path of the video file outputLastfilename =NewFileName (); Mediarecorder.setoutputfile (lastfilename);Try { //Prepare to recordMediarecorder.prepare ();//Start RecordingMediarecorder.start ();} Catch(IllegalStateException e) {//TODO auto-generated Catch blocke.printstacktrace ();} Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();} End shooting:if(Mediarecorder! =NULL) { //Stopmediarecorder.stop (); Mediarecorder.release (); Mediarecorder=NULL; } 

Your own Package class:

 PackageZyf.demo.moviedemo;ImportJava.io.File;Importjava.io.IOException;ImportJava.util.Timer;ImportJava.util.TimerTask;ImportAndroid.media.MediaRecorder;ImportAndroid.view.SurfaceView; Public classMovierecorder {PrivateMediarecorder Mediarecorder;Booleanisrecording; Public voidstartrecording (Surfaceview surfaceview) {Mediarecorder=NewMediarecorder ();//Create a Mediarecorder object//set the recording video source to cameraMediarecorder.setvideosource (MediaRecorder.VideoSource.CAMERA);//set the format of the video after recording is complete THREE_GPP to 3gp.mpeg_4 for MP4Mediarecorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP);//set the recorded video encoding h263 H264Mediarecorder.setvideoencoder (MediaRecorder.VideoEncoder.H264);//sets the resolution of the video recording. Must be placed behind the set encoding and format, otherwise the errorMediarecorder.setvideosize (176, 144); //sets the recorded video frame rate. Must be placed behind the set encoding and format, otherwise the errorMediarecorder.setvideoframerate (20); Mediarecorder.setpreviewdisplay (Surfaceview.getholder (). Getsurface ()); //set the path of the video file outputLastfilename =NewFileName (); Mediarecorder.setoutputfile (lastfilename);Try { //Prepare to recordMediarecorder.prepare ();//Start RecordingMediarecorder.start ();} Catch(IllegalStateException e) {//TODO auto-generated Catch blocke.printstacktrace ();} Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();} IsRecording=true; Timesize= 0; a timer=NewTimer (); Timer.schedule (NewTimerTask () {@Override Public voidrun () {//TODO auto-generated Method Stubtimesize++; } }, 0,1000); } timer timer; intTimesize = 0; PrivateString Lastfilename; Public voidstoprecording () {if(Mediarecorder! =NULL) { //Stopmediarecorder.stop (); Mediarecorder.release (); Mediarecorder=NULL; Timer.cancel ();if(NULL! = Lastfilename &&! "". Equals (Lastfilename)) {File F=NewFile (lastfilename); String name= F.getname (). substring (0, F.getname (). LastIndexOf (". 3gp")); Name+ = "_" + timesize + "s.3gp"; String NewPath= F.getparentfile (). GetAbsolutePath () + "/" +name;if(F.renameto (NewFile (NewPath))) { inti = 0; I++; } } } }  PublicString NewFileName () {Try { returnFile.createtempfile ("/mov_", ". 3gp"). GetAbsolutePath (); } Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();return NULL; } }  Public voidrelease () {if(Mediarecorder! =NULL) { //Stopmediarecorder.stop (); Mediarecorder.release (); Mediarecorder=NULL; } } } 

How to Play:

 Public voidPlay (String fileName, Surfaceview view) {MPlayer=NewMediaPlayer (); Mplayer.setaudiostreamtype (Audiomanager.stream_music); Mplayer.setdisplay (View.getholder ());//define a Surfaceview to play itMplayer.setoncompletionlistener (NewOncompletionlistener () {@Override Public voidoncompletion (MediaPlayer arg0) {stop ();//Canvas.drawcolor (color.transparent,//PorterDuff.Mode.CLEAR); } }); Try{mplayer.setdatasource (fileName); Mplayer.prepare ();}Catch(IllegalStateException e) {//TODO auto-generated Catch blocke.printstacktrace ();} Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();} Mplayer.start (); When it finishes playing: Public voidStop () {if(MPlayer! =NULL) {mplayer.release (); MPlayer=NULL; } } 

Enclosed source code: Http://pan.baidu.com/s/1dDuI2HF Extract Code: CMM6

Android calls phone camera using Mediarecorder video and play

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.