Android Recording Video

Source: Internet
Author: User

We generally take data directly from the camera and microphone, encoded and saved as files. Android video recording requires the use of Mediarecorder,mediarecorder In addition to recording audio, and can also be used to record video.

As shown in the following:


One for the recording process, you can see the recording time displayed at the top of the screen, and the latter to stop recording the video.


Then the recorded video can be found in the phone's SD card, as shown in:



Video recording steps:

1) Call the Mediarecorder object's Setvideoencoder (), Setvideoencodingbitrate (intbitrate), setvideoframerate to set the encoded format of the recorded video, the encoding bit rate, How many frames per second, etc., these parameters will control the quality of the recorded video, the size of the file. In general, the better the video quality, the larger the video file.

2) Call Mediarecorder's Setpreviewdisplay (SURFACESV) method to set which Surfaceview to use to display the video preview.

The instance uses Mediarecorder to record video:


Import Android.annotation.suppresslint;import Android.app.activity;import Android.graphics.pixelformat;import Android.hardware.camera;import Android.media.mediarecorder;import Android.os.bundle;import android.os.Environment ; Import Android.os.handler;import Android.view.*;import Android.view.surfaceholder.callback;import Android.widget.button;import Android.widget.linearlayout;import Android.widget.textview;import Android.widget.toast;import Java.io.file;import Java.text.simpledateformat;import java.util.Calendar;@ Suppresslint ("SimpleDateFormat") public class MyActivity extends Activity implements Callback {private Surfaceview Msurfaceview;private button mbtnstartstop;//start Stop Recording button private Boolean MSTARTEDFLG = False;private Mediarecorder mrecorder;//recording Video class private Surfaceholder msurfaceholder;//Show video private Camera camera;private TextView timeview;// Show recording time at the top of the screen private int times = 0; @SuppressLint ("Handlerleak") private Handler Handler = new Handler () {public void Handlemes Sage (android.os.MessAge msg} {switch (msg.what) {case 1://start recording Timeview.settext (time + "s"); Break;case 2://Record 8s End Mrecorder.stop (); Mrecorder . Reset (); You can reuse the object Bymbtnstartstop.settext ("Start"); mstartedflg = False;time = 0;timeview.settext (time + "s"); BR Eak;case 3://Physical examination End time = 0;timeview.settext (time + "s"); break;};}; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature ( Window.feature_no_title);//Remove the title bar GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//Set Full screen GetWindow (). SetFormat (pixelformat.translucent); Choose to support semitransparent mode, which is used in surfaceview activity. Setcontentview (R.layout.main);//Load Layout Timeview = (TextView) Findviewbyid (r.id.time); Msurfaceview = (Surfaceview) Findviewbyid (r.id.surfaceview); mbtnstartstop = (Button) Findviewbyid (R.ID.BTN); Mbtnstartstop.setonclicklistener ( New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubif (!mSTARTEDFLG) {//start if (Mrecorder = = null) {Mrecorder = new Mediarecorder ();//Create Mediarecorder object}try {camera.unlock (); MRec Order.setcamera (camera); Mrecorder.setaudiosource (MediaRecorder.AudioSource.CAMCORDER);// These two need to be placed before Setoutputformat Mrecorder.setvideosource (MediaRecorder.VideoSource.CAMERA);//Set the recording video source to camera Mrecorder.setorientationhint;//Set Output file Formatmrecorder.setoutputformat ( MEDIARECORDER.OUTPUTFORMAT.MPEG_4)///Set the package format of the video after recording three_gpp to 3gp.mpeg_4 for mp4// These two need to be placed after Setoutputformat Mrecorder.setaudioencoder (MediaRecorder.AudioEncoder.AMR_NB); Mrecorder.setvideoencoder (MediaRecorder.VideoEncoder.MPEG_4_SP);//Set the recorded video encoding H263mrecorder.setvideosize (800, 480);//Set the resolution of the video recording. Must be placed behind the setup encoding and format, otherwise error mrecorder.setvideoframerate (30);//Set the recorded video frame rate. Must be placed behind the setup encoding and format, otherwise error mrecorder.setmaxduration (8000);//Set Maximum recording time Mrecorder.setpreviewdisplay ( Msurfaceholder.getsurface ());//Set output file pathstring path = Getsdpath (); if (path! = null) {file DIR = new file (path + "/recordtest"); if (!dir.exists ()) {Dir.mkdir ();} Path = dir + "/" + getDate () + ". mp4"; Toast.maketext (Myactivity.this, Path,toast.length_long). Show (); mrecorder.setoutputfile (path); Mrecorder.prepare ( );//Prepare to record mrecorder.start (); Start recording new Thread (new Runnable () {@Overridepublic void run () {while (Time < 8) {try {time++; Thread.Sleep (+); handler.sendemptymessage (1);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Handler.sendemptymessage (2);}}). Start (); MSTARTEDFLG = True;mbtnstartstop.settext ("Stop");}} catch (Exception e) {e.printstacktrace ();}} else {//STOPIF (MSTARTEDFLG) {try {mrecorder.stop (); Mrecorder.reset ();//Can reuse the object by//going back to//s Etaudiosource () stepmbtnstartstop.settext ("Start"); handler.sendemptymessagedelayed (3, 1000);} catch (Exception e) {e.printstacktrace ();}} MSTARTEDFLG = false; Set button Status Flag}}); Surfaceholder holder = Msurfaceview.getholder ();//acquired Holderholder.addcallback (this); Holder joins the callback interface Holder.settype (Surfaceholder.surface_type_push_buffers);//Settype must be set, or error.} /** * Use time to name the recording * * @return */public static String getDate () {Calendar CA = calendar.getinstance (); SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmss"); String date = Sdf.format (Ca.gettimeinmillis ()); return date;} /** * Get SD Path * * @return */public String Getsdpath () {File Sddir = Null;boolean sdcardexist = environment.getexternals Toragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED); Determine if the SD card exists if (sdcardexist) {sddir = Environment.getexternalstoragedirectory ();//Get with directory//Toast.maketext (this, Sddir.tostring (), Toast.length_long). Show (); return sddir.tostring ();} else {Toast.maketext (this, "No SD card", Toast.length_long). Show (); return null;} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width,int height) {camera = Camera.open ();//Get Camera instance try {camera.setpreviewdisplay (holder); Msurfaceview.setlayoutparams (new Linearlayout.layoutparams (width, height));} catch (Exception e) {//If an exception occurs, release the Camera object camera. Release ();} Camera.setdisplayorientation (90);//Set Preview video always vertical screen//Start preview function Camera.startpreview ();//Will Holder, This holder for the beginning of the holder in OnCreate, assigns it to Msurfaceholdermsurfaceholder = holder;} @Overridepublic void surfacecreated (Surfaceholder holder) {//Will holder, this holder to start OnCreate in holder, Assign it to Msurfaceholdermsurfaceholder = holder;} @Overridepublic void surfacedestroyed (Surfaceholder holder) {//TODO auto-generated method stub// Surfacedestroyed when the object is set to Nullmsurfaceview = Null;msurfaceholder = Null;if (Mrecorder! = null) {mrecorder.release ();// Now the object cannot is Reusedmrecorder = null;} if (camera! = null) {camera.release (); camera = null;}}}
The layout file for the XML is:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout 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" android:orientation= "vertical" android:background= "@android: Color/white" > <textview Android:id= "@+id/time" android:layout_gravity= "center" android:layout_width= "Wrap_content" Android:la yout_height= "Wrap_content" android:textsize= "16sp" android:text= "0 S" android:textcolor= "@android: Co Lor/background_dark "/> <surfaceview android:id=" @+id/surfaceview "android:layout_width=" fill_parent        "Android:layout_height=" 0dip "android:layout_weight=" 1 "/> <button android:id=" @+id/btn "        Android:layout_width= "101DP" android:layout_height= "wrap_content" android:layout_gravity= "center"     android:layout_weight= "0.02"   android:text= "Start" tools:context= ". Mainactivity "/></linearlayout>



Android Recording Video

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.