Android Imitation micro-letter shooting short video _android

Source: Internet
Author: User

Recent projects need to add a short video function, the function is set to resemble the micro-letter, click Start Shooting, set the longest shooting time, after the research finally realized this function, and then share with you, hope to help you.

1. Video Recording custom controls:

/** * Video Playback control/public class Movierecorderview extends LinearLayout implements Onerrorlistener {private Surfaceview M
 Surfaceview;
 Private Surfaceholder Msurfaceholder;
 Private ProgressBar Mprogressbar;
 Private Mediarecorder Mmediarecorder;
 Private Camera Mcamera; Private timer mtimer;//Timer private Onrecordfinishlistener monrecordfinishlistener;//recording complete callback interface private int mwidth;//video points
 Discrimination width private int mheight;//Video resolution height Private Boolean isopencamera;//whether to open the camera at the beginning of private int mrecordmaxtime;//one shot for the longest time private int mtimecount;//time count private file Mvecordfile = null;//file Public Movierecorderview (context context) {This (
 context, NULL);
 Public Movierecorderview (context, AttributeSet attrs) {This (context, attrs, 0); @SuppressLint ("Newapi") public Movierecorderview (context, AttributeSet attrs, int defstyle) {Super (context,
 Attrs, Defstyle);
 TypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.movierecorderview, Defstyle, 0); Mwidth= A.getinteger (R.styleable.movierecorderview_width, 320);//Default mheight = A.getinteger ( R.styleable.movierecorderview_height, 240);//Default Isopencamera = A.getboolean (r.styleable.movierecorderview_is_ Open_camera, True);//default Open Mrecordmaxtime = A.getinteger (R.styleable.movierecorderview_record_max_time, 10);
 Ayoutinflater.from (context)-Inflate (R.layout.movie_recorder_view, this);
 Msurfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview);
 Mprogressbar = (ProgressBar) Findviewbyid (R.id.progressbar);
 Mprogressbar.setmax (Mrecordmaxtime)//Set the progress bar the most significant msurfaceholder = Msurfaceview.getholder ();
 Msurfaceholder.addcallback (New Customcallback ());
 Msurfaceholder.settype (surfaceholder.surface_type_push_buffers);
 A.recycle (); }/** * */Private class Customcallback implements Callback {@Override public void surfacecreated (Surfaceholder ho
  Lder) {if (!isopencamera) return;
  try {Initcamera ();
  catch (IOException e) {e.printstacktrace (); }} @OvErride public void surfacechanged (surfaceholder holder, int format, int width, int height) {} @Override public void
  Surfacedestroyed (Surfaceholder holder) {if (!isopencamera) return;
 Freecameraresource ();
 }/** * Initialize camera/private void Initcamera () throws IOException {if (Mcamera!= null) {Freecameraresource ();
 try {Mcamera = Camera.open ();
  catch (Exception e) {e.printstacktrace ();
 Freecameraresource ();
 } if (Mcamera = null) return;
 Setcameraparams ();
 Mcamera.setdisplayorientation (90);
 Mcamera.setpreviewdisplay (Msurfaceholder);
 Mcamera.startpreview ();
 Mcamera.unlock (); /** * Set the camera for the vertical screen */private void Setcameraparams () {if (Mcamera!= null) {Parameters params = Mcamera.getparamete
  RS ();
  Params.set ("Orientation", "portrait");
 Mcamera.setparameters (params);
  }/** * Free camera resource/private void Freecameraresource () {if (Mcamera!= null) {mcamera.setpreviewcallback (null);
  Mcamera.stoppreview ();
  Mcamera.lock (); MCamera.release ();
 Mcamera = null;
  } private void Createrecorddir () {//Recorded video save folder file Sampledir = new file (Environment.getexternalstoragedirectory ()
 + File.separator + "ysb/video/")//Record video save address if (!sampledir.exists ()) {sampledir.mkdirs ();
 } File vecorddir = Sampledir; Create file try {mvecordfile = File.createtempfile ("Recording", ". mp4", vecorddir);//MP4 recorded video file} catch (IOException
 e) {e.printstacktrace (); }/** * Initialization * @throws IOException/@SuppressLint ("Newapi") private void Initrecord () throws IOException {mmed
 Iarecorder = new Mediarecorder ();
 Mmediarecorder.reset ();
 if (Mcamera!= null) Mmediarecorder.setcamera (Mcamera);
 Mmediarecorder.setonerrorlistener (this);
 Mmediarecorder.setpreviewdisplay (Msurfaceholder.getsurface ());
 Mmediarecorder.setvideosource (Videosource.camera);//Video source Mmediarecorder.setaudiosource (AudioSource.MIC);//audio source Mmediarecorder.setoutputformat (outputformat.mpeg_4);//Video output format Mmediarecorder.setaudioencoder (AudioENcoder. AMR_NB)//Audio format mmediarecorder.setvideosize (mwidth, mheight);//Set Resolution://Mmediarecorder.setvideoframerate (16);// I took it off, and it didn't feel good. Mmediarecorder.setvideoencodingbitrate (1 * 1024 * 1024 * 100);/set frame frequency, then clear the Mmediarecorder.setorienta Tionhint (90);//output rotation 90 degrees, keep the vertical screen recording mmediarecorder.setvideoencoder (VIDEOENCODER.MPEG_4_SP);//video recording format//
 Mediarecorder.setmaxduration (Constant.maxvediotime * 1000);
 Mmediarecorder.setoutputfile (Mvecordfile.getabsolutepath ());
 Mmediarecorder.prepare ();
 try {mmediarecorder.start ();
 catch (IllegalStateException e) {e.printstacktrace ();
 catch (RuntimeException e) {e.printstacktrace ();
 catch (Exception e) {e.printstacktrace (); /** * Start Recording video * @param fileName * Video storage location * @param Onrecordfinishlistener * After the specified time to the callback interface * * public void Recor
 D (Final Onrecordfinishlistener onrecordfinishlistener) {this.monrecordfinishlistener = Onrecordfinishlistener;
 Createrecorddir (); try {if (!isopencamera)//If the camera is not turned on, open InitcamerA ();
  Initrecord ();
  Mtimecount = 0;//Time counter re-assign Mtimer = new Timer ();
   Mtimer.schedule (New TimerTask () {@Override public void run () {mtimecount++;
   Mprogressbar.setprogress (Mtimecount)//Set progress bar if (Mtimecount = = Mrecordmaxtime) {//Reach specified time, stop shooting Stop ();
   if (Monrecordfinishlistener!= null) monrecordfinishlistener.onrecordfinish ();
 }}, 0, 1000);
 catch (IOException e) {e.printstacktrace ();
 }/** * Stop shooting/public void Stop () {Stoprecord ();
 Releaserecord ();
 Freecameraresource ();
 /** * Stop recording/public void Stoprecord () {mprogressbar.setprogress (0);
 if (Mtimer!= null) mtimer.cancel ();
  if (Mmediarecorder!= null) {//set does not collapse after mmediarecorder.setonerrorlistener (null);
  Mmediarecorder.setpreviewdisplay (NULL);
  try {mmediarecorder.stop ();
  catch (IllegalStateException e) {e.printstacktrace ();
  catch (RuntimeException e) {e.printstacktrace ();
  catch (Exception e) {e.printstacktrace (); }}/** * freeResource/private void Releaserecord () {if (Mmediarecorder!= null) {Mmediarecorder.setonerrorlistener (null);
  try {mmediarecorder.release ();
  catch (IllegalStateException e) {e.printstacktrace ();
  catch (Exception e) {e.printstacktrace ();
 } Mmediarecorder = null;
 public int Gettimecount () {return mtimecount;
 //Returns the recorded video file public file Getmvecordfile () {return mvecordfile;
 /** * Recording completes callback interface/public interface Onrecordfinishlistener {public void onrecordfinish ();
 @Override public void OnError (Mediarecorder mr, int what, int extra) {try {if (Mr!= null) Mr.reset ();
 catch (IllegalStateException e) {e.printstacktrace ();
 catch (Exception e) {e.printstacktrace ();
 }
 }
}

2. Video recording interface file Movie_recorder_view.xml:

<?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:background= "@android: Color/background_dark"
 android:o rientation= "vertical" >
 <surfaceview 
  android:id= "@+id/surfaceview" 
  Fill_parent " 
  android:layout_height=" 0DP "
  android:layout_weight=" 1 "
  />
 <progressbar
 android:id= "@+id/progressbar"
 style= "Android:attr/progressbarstylehorizontal"
 android:layout_ Width= "Match_parent"
 android:layout_height= "2DP" 
 />
</LinearLayout>

With these preparations, we can begin to design our video recording function. PS: The above code is taken to the Internet, here to pay tribute to Daniel.

3. Shoot the main interface, the filming interface has two parts, above is the video capture control display, the following is the user clicks on the shooting button, profile: Activity_main.xml.

<?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:background= "@android: Color/white"
 android:orientation= " Vertical ">
<com.example.wechatvideorecorddemo.movierecorderview
 android:id=" @+id/ Movierecorderview "
 android:layout_width=" match_parent "
 android:layout_height=" 0DP "
 android: layout_weight= "1"
 android:layout_margin= "3DP"/>
 <button
 android:id= "@+id/shoot_button"
 android:layout_width= "wrap_content"
 android:layout_height= "wrap_content"
 android:layout_ gravity= "center" android:background= "@drawable/bg_movie_add_shoot"
 android:text= "hold the Racket" 
 android: Textcolor= "#20b6ff"/>
</LinearLayout>

4. With the view of the main interface, we will begin to write our activity file Mainactivity.java:

public class Mainactivity extends activity {private Movierecorderview mrecorderview;//video recording control private Button mshootbtn;
 Video Start Recording button Private Boolean isfinish = true; Private Boolean success = false;//prevents multiple jump events from completing a recording @Override protected void OnCreate (Bundle savedinstancestate) {super.
 OnCreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);
 Mrecorderview = (Movierecorderview) Findviewbyid (R.id.movierecorderview);
 MSHOOTBTN = (Button) Findviewbyid (R.id.shoot_button); User-Monitored Mshootbtn.setontouchlistener by event (new Ontouchlistener () {@Override public boolean ontouch (View V, motionevent Event) {if (event.getaction () = = Motionevent.action_down) {//user presses the shoot button Mshootbtn.setbackgroundresource (r.drawable.bg_
   Movie_add_shoot_select); Mrecorderview.record (New Onrecordfinishlistener () {@Override public void Onrecordfinish () {if (!success&&am
   P;mrecorderview.gettimecount () <10) {//To determine whether the user pressed the time is greater than 10 seconds success = true;
    Handler.sendemptymessage (1);
}   }
   }); else if (event.getaction () = = motionevent.action_up) {//The user lifts the shot button Mshootbtn.setbackgroundresource (r.drawable.bg_
   Movie_add_shoot);
    if (Mrecorderview.gettimecount () > 3) {//whether the user presses the time is greater than 3 seconds if (!success) {success = true;
   Handler.sendemptymessage (1);
   } else {success = false; if (mrecorderview.getmvecordfile ()!= null) mrecorderview.getmvecordfile (). Delete ();//Remove the recorded short video mrecorderview.stop (
   //Stop Recording Toast.maketext (Mainactivity.this, "video recording time is too Short", Toast.length_short). Show ();
  } return true;
 }
 });
 @Override public void Onresume () {super.onresume ();
 Isfinish = true;  if (mrecorderview.getmvecordfile ()!= null) mrecorderview.getmvecordfile (). Delete ()//@Override public void after video use
 Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate);
 Isfinish = false;
 Success = false;
 Mrecorderview.stop ()//Stop recording} @Override public void OnPause () {super.onpause ();
 @Override public void OnDestroy () {Super.ondestroy (); Private Handler Handler = new Handler () {@Override public void Handlemessage (msg) {if (success) {Finisha
  Ctivity ();
 }
 }
 };
  After the video recording is finished, the function of the jump is private void finishactivity () {if (isfinish) {mrecorderview.stop ();
  Intent Intent = new Intent (this, successactivity.class);
  Bundle Bundle = new Bundle ();
  Bundle.putstring ("Text", Mrecorderview.getmvecordfile (). toString ());
  Intent.putextras (bundle);
 StartActivity (Intent);
 } success = false;
  /** * Recording complete callback/public interface Onshootcompletionlistener {public void onshootsuccess (String path, int second);
 public void Onshootfailure ();
 }
}

Here we have a short copy of the micro-letter video shoot is already done, then let's examine how we recorded the effect, the following I provide Android video playback control (Videoview) to show you how to play the recorded short video.

5. Activity_success.xml of the video playback profile:

<?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:background= "@android: Color/white" android:orientation= "vertical" > <textview android: Id= "@+id/text" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_gravity= " Center "android:text=" @string/app_name "/> <linearlayout android:layout_width=" Match_parent "Android:layout_ height= "wrap_content" android:orientation= "horizontal" > <button android:id= "@+id/button1" Android:layout_wi Dth= "Match_parent" android:layout_height= "Wrap_content" android:layout_weight= "1" android:gravity= "Center" Android
  :p adding= "5DP" android:text= "Play"/> <button android:id= "@+id/button2" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" Android:layout_weight= "1" android:gravity= "center" android:padding= "5DP" android:text= "suspend"/> <button "android:id=" @+id/button3 "android:layout_width=" match_parent "android:layout_height=" Wrap_content "android:layout_weight=" 1 "a ndroid:gravity= "center" android:padding= "5DP" android:text= "Replay"/> <button android:id= "@+id/button4" and Roid:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_weight= "1" android:gravity= " Center "android:padding=" 5DP "android:text=" video Length "/> </LinearLayout> <videoview android:id=" @+id/vide
 OView1 "android:layout_width=" wrap_content "android:layout_height=" 500DP "/> </LinearLayout>

6. Control code for video playback Successactivity.java:

public class Successactivity extends activity implements onclicklistener{private TextView text;//video save path Private Butto  N button1;//Play switch private button button2;//pause switch private button button3;//Replay switch private button button4;//Video size switch private Videoview videoview1;//video playback control private String file;//video path @Override protected void OnCreate (Bundle savedinstancestate)
 {super.oncreate (savedinstancestate);
 Setcontentview (r.layout.activity_success);
 Bundle Bundle = Getintent (). Getextras ();
 File = bundle.getstring ("text");//Get Shot short video save Address init ();
 SetValue ();
 }//Initialize private void init () {text = (TextView) Findviewbyid (R.id.text);
 Button1 = (Button) Findviewbyid (R.id.button1);
 Button2 = (Button) Findviewbyid (R.id.button2);
 Button3 = (Button) Findviewbyid (R.id.button3);
 Button4 = (Button) Findviewbyid (R.ID.BUTTON4);
 VideoView1 = (videoview) Findviewbyid (R.ID.VIDEOVIEW1);
 //Set private void SetValue () {text.settext (file);
 Button1.setonclicklistener (this); Button2.setonclickliStener (this);
 Button3.setonclicklistener (this);
 Button4.setonclicklistener (this);
 Videoview1.setvideopath (file);
  @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.button1:videoview1.start ();
 Break 
  Case R.id.button2:videoview1.pause ();
 Break
  Case R.id.button3:videoview1.resume ();
  Videoview1.start ();
 Break
  Case R.id.button4:toast.maketext (This, "video length:" + (Videoview1.getduration ()/1024) + "M", Toast.length_short). Show ();
 Break
 Default:break;
 }
 } 
}

7. Add Permissions:

<!--video recording permissions star-->
<!--camera-->
<uses-permission android:name= "Android.permission.CAMERA"/ >
<!--audio-->
<uses-permission android:name= "Android.permission.RECORD_AUDIO"/>
<!--SD card Write permission-->
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<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 "/>
<!--video recording permission End-->

Functional Interface Screenshot:

OK, here about shooting short video knowledge and everyone to share, the specific implementation is very simple, I believe you see here has been learned, of course, if you have any questions, you can leave a message to discuss. Finally to share a demo download address, convenient for everyone to download learning, download address: Http://wd.jb51.net:81//201612/yuanma/WeChatVideoRecordDemo_jb51.rar

Above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

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.