Simple recording function with Mediarecorder

Source: Internet
Author: User

Idea: Define a surfaceview to display a preview, launch a preview with the camera object in the Surfaceholder callback, and then call Mediarecorder to record it. Just realize the simple recording start and stop function, the top can display the time of recording, still need to be perfected.

The code is as follows:

Add the following permissions in Androidmanifest.xml:

<uses-permission android:name= "Android.permission.CAMERA"/><uses-permission android:name= " Android.permission.RECORD_AUDIO "/><uses-permission android:name=" android.permission.MOUNT_UNMOUNT_ Filesystems "/><uses-permission android:name=" Android.permission.READ_EXTERNAL_STORAGE "/>< Uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/><!--hardware support--><uses-feature Android:name= "Android.hardware.camera"/><uses-feature android:name= "Android.hardware.camera.autofocus"/ >
activity_main.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" match_parent "> <Surf Aceview android:id= "@+id/camera_preview" android:layout_width= "Match_parent" android:layout_height= "M Atch_parent "/> <linearlayout android:layout_width=" wrap_content "android:layout_height=" Wrap_conte NT "android:layout_alignparenttop=" true "android:layout_centerhorizontal=" true "android:orientation=" Horizontal "> <textview android:id=" @+id/timestamp_minute_prefix "android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:textcolor=" #7F00FF "Android:te            Xtsize= "30sp" android:text= "0"/> <textview android:id= "@+id/timestamp_minute_text"   Android:layout_width= "Wrap_content"         android:layout_height= "Wrap_content" android:textcolor= "#7F00FF" android:textsize= "30SP" android:text= "0"/> <textview android:layout_width= "Wrap_content" android:layou t_height= "Wrap_content" android:textcolor= "#7F00FF" android:textsize= "30SP" android:text= ":"/> <textview android:id= "@+id/timestamp_second_prefix" android:layout_width= "Wrap_co Ntent "android:layout_height=" wrap_content "android:textcolor=" #7F00FF "android:textsize=            "30SP" android:text= "0"/> <textview android:id= "@+id/timestamp_second_text"             Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:textcolor= "#7F00FF" Android:textsize= "30sp" android:text= "0"/> </LinearLayout> <imagebutton an Droid:id= "@+id/record_shUtter "android:layout_width=" 64DP "android:layout_height=" 64DP "android:layout_alignparentbottom=" Tru E "android:layout_centerhorizontal=" true "android:layout_marginbottom=" 15DP "android:background=" @and Roid:color/transparent "android:scaletype=" Centercrop "android:src=" @drawable/recording_shutter "/></R Elativelayout>
mainactivity.java
Package Com.jackie.videorecorder;import Java.io.file;import Android.app.activity;import Android.hardware.Camera; Import Android.hardware.camera.parameters;import Android.hardware.camera.size;import Android.media.MediaRecorder; Import Android.os.bundle;import android.os.environment;import Android.os.handler;import Android.util.Log;import Android.view.surfaceholder;import Android.view.surfaceview;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.imagebutton;import Android.widget.textview;import Org.w3c.dom.text;public class Mainactivity extends Activity implements Onclicklistener {private Surfaceview Mcamerapre    View    Private Surfaceholder Msurfaceholder;    Private ImageButton Mshutter;    Private TextView Mminuteprefix;    Private TextView Mminutetext;    Private TextView Msecondprefix;    Private TextView Msecondtext;    Private Camera Mcamera;    Private Mediarecorder Mrecorder;    Private final static int camera_id = 0; Private Boolean MIsRecording = false;    Private Boolean missufacecreated = false;    private static final String TAG = "Jackie";    Private Handler Mhandler = new Handler ();        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mcamerapreview = (Surfaceview) Findviewbyid (R.id.camera_preview);        Mminuteprefix = (TextView) Findviewbyid (R.id.timestamp_minute_prefix);        Mminutetext = (TextView) Findviewbyid (R.id.timestamp_minute_text);        Msecondprefix = (TextView) Findviewbyid (R.id.timestamp_second_prefix);        Msecondtext = (TextView) Findviewbyid (R.id.timestamp_second_text);        Msurfaceholder = Mcamerapreview.getholder ();        Msurfaceholder.addcallback (Msurfacecallback);        Msurfaceholder.settype (surfaceholder.surface_type_push_buffers);        Mshutter = (ImageButton) Findviewbyid (r.id.record_shutter);    Mshutter.setonclicklistener (this); } @Override Protected void OnPause () {super.onpause ();        if (misrecording) {stoprecording ();    } stoppreview ();  } private Surfaceholder.callback Msurfacecallback = new Surfaceholder.callback () {@Override public void        Surfacedestroyed (Surfaceholder holder) {missufacecreated = false;        } @Override public void surfacecreated (Surfaceholder holder) {missufacecreated = true;            } @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {        Startpreview ();    }    };            Start preview private void Startpreview () {//Guaranteed only one Camera object if (Mcamera! = NULL | |!missufacecreated) {            LOG.D (TAG, "Startpreview'll Return");        Return        } Mcamera = Camera.open (camera_id);        Parameters Parameters = Mcamera.getparameters (); Size size = Getbestpreviewsize (Camerautils.preview_width, Camerautils.preview_HEIGHT, parameters);        if (size! = NULL) {parameters.setpreviewsize (size.width, size.height);        } parameters.setfocusmode (Parameters.focus_mode_continuous_video);        Parameters.setpreviewframerate (20);        Set Camera preview Direction mcamera.setdisplayorientation (90);        Mcamera.setparameters (parameters);        try {mcamera.setpreviewdisplay (msurfaceholder);//mcamera.setpreviewcallback (Mpreviewcallback);        } catch (Exception e) {log.d (TAG, E.getmessage ());    } mcamera.startpreview (); } private void Stoppreview () {//Release camera object if (Mcamera! = null) {try {Mcamer            A.setpreviewdisplay (NULL);            } catch (Exception e) {log.e (TAG, E.getmessage ());            } mcamera.stoppreview ();            Mcamera.release ();        Mcamera = null; }} private Camera.size getbestpreviewsize (int width, int height, camera.parameters parameteRS) {camera.size result = null; For (Camera.size size:parameters.getSupportedPreviewSizes ()) {if (size.width <= width && size.hei                Ght <= height) {if (result = = null) {result = size;                    } else {int resultarea = result.width * result.height;                    int Newarea = Size.width * size.height;                    if (Newarea > Resultarea) {result = size;    }}}} return result;        @Override public void OnClick (View v) {if (misrecording) {stoprecording ();            } else {initmediarecorder ();            Startrecording ();        After starting recording, every 1s to update the video timestamp mhandler.postdelayed (mtimestamprunnable, 1000);        }} private void Initmediarecorder () {mrecorder = new Mediarecorder ();//instantiation of Mcamera.unlock (); Set came for recorderRA object to ensure that the video is consistent with the orientation of the preview Mrecorder.setcamera (Mcamera);  Mrecorder.setorientationhint (90); Change the saved video file playback when the horizontal screen (without this sentence, video file playback angle is reversed) mrecorder.setaudiosource (MediaRecorder.AudioSource.MIC); Set the acquisition of Sound Mrecorder.setvideosource (MediaRecorder.VideoSource.CAMERA) from the microphone;  Set the image capture from the camera Mrecorder.setoutputformat (MediaRecorder.OutputFormat.MPEG_4); Set the output format of the video to MP4 Mrecorder.setaudioencoder (MediaRecorder.AudioEncoder.DEFAULT); Sets the encoding format for audio Mrecorder.setvideoencoder (MediaRecorder.VideoEncoder.H264);  Set the encoding format for the video mrecorder.setvideosize (176, 144); Set the video size mrecorder.setvideoframerate (20); Set frame rate//mrecorder.setmaxduration (10000);        Set the maximum recording time to 10s Mrecorder.setpreviewdisplay (Msurfaceholder.getsurface ()); Set the video storage path File File = new file (Environment.getexternalstoragepublicdirectory (environment.directory_movies) + file.        Separator + "Videorecorder"); if (!file.exists ()) {//Multi-level folder creation File.mkDirs ();    } mrecorder.setoutputfile (File.getpath () + File.separator + "vid_" + system.currenttimemillis () + ". mp4");                } private void Startrecording () {if (Mrecorder! = null) {try {mrecorder.prepare ();            Mrecorder.start ();                } catch (Exception e) {misrecording = false;            LOG.E (TAG, E.getmessage ());        }} mshutter.setimagedrawable (Getresources (). getdrawable (R.DRAWABLE.RECORDING_SHUTTER_HL));    Misrecording = true;        } private void Stoprecording () {if (Mcamera! = null) {Mcamera.lock ();            } if (Mrecorder! = null) {mrecorder.stop ();            Mrecorder.release ();        Mrecorder = null;        } mshutter.setimagedrawable (Getresources (). getdrawable (R.drawable.recording_shutter));        Misrecording = false;        Mhandler.removecallbacks (mtimestamprunnable); Restore the recording time Mminuteprefix.setvIsibility (view.visible);        Mminutetext.settext ("0");        Msecondprefix.setvisibility (view.visible);        Msecondtext.settext ("0");    Restart preview Startpreview (); } private Runnable mtimestamprunnable = new Runnable () {@Override public void run () {Updatet            Imestamp ();        Mhandler.postdelayed (this, 1000);    }    };        private void Updatetimestamp () {int second = Integer.parseint (Msecondtext.gettext (). toString ());        int minute = Integer.parseint (Mminutetext.gettext (). toString ());        second++;        LOG.D (TAG, "second:" + second);        if (second <) {Msecondtext.settext (string.valueof (second));            } else if (second >= && Second <) {msecondprefix.setvisibility (view.gone);        Msecondtext.settext (string.valueof (second));            } else if (second >=) {msecondprefix.setvisibility (view.visible);      Msecondtext.settext ("0");      minute++;        Mminutetext.settext (string.valueof (minute));        } else if (minute >=) {mminuteprefix.setvisibility (view.gone); }    }}

The effect is as follows:



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Simple recording function with Mediarecorder

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.