Java Making imitation micro-letter recording small video control _java

Source: Internet
Author: User

This article is a control that uses Mediarecorder to record small video, you can set the time, space size of the video recording, and whether to turn on the camera at the beginning. This control is a composite control that inherits from LinearLayout and implements the Android.media.MediaRecorder.OnErrorListener interface to prevent errors.

Small video Recording interface

Movierecorderview.java

Import Java.io.File;
Import java.io.IOException;
Import Java.util.Timer;
 
Import Java.util.TimerTask;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.hardware.Camera;
Import Android.hardware.Camera.Parameters;
Import Android.media.MediaRecorder;
Import Android.media.MediaRecorder.AudioEncoder;
Import Android.media.MediaRecorder.AudioSource;
Import Android.media.MediaRecorder.OnErrorListener;
Import Android.media.MediaRecorder.OutputFormat;
Import Android.media.MediaRecorder.VideoEncoder;
Import Android.media.MediaRecorder.VideoSource;
Import Android.util.AttributeSet;
Import Android.view.LayoutInflater;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceHolder.Callback;
Import Android.view.SurfaceView;
Import Android.widget.LinearLayout;
 
Import Android.widget.ProgressBar;
Import COM.CONTRON.DGYJ.R;
Import Com.contron.dgyj.common.Globals;
Import Com.contron.dgyj.im.ImGlobal;
 
Import Com.lidroid.xutils.util.LogUtils; /** * Video Playback control *
 * @author Liuyinjun * * @date 2015-2-5/public class Movierecorderview extends LinearLayout implements Onerrorlist
  Ener {private Surfaceview msurfaceview;
  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 resolution width private int mheight;//Video resolution height Private Boolean isopencamera;//whether to open the camera at first private int mrecordmaxtime;//once Shooting for the longest time private int mtimecount;//time count private file Mvecordfile = null;//file public movierecorderview (context Conte
  XT) {This (context, NULL);
  Public Movierecorderview (context, AttributeSet attrs) {This (context, attrs, 0);
 
    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.moviereco Rderview_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);//default to ten Layoutinflater.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 (); /** * * * * * @author liuyinjun * * @date 2015-2-5/Private class Customcallback implements Callback {@Override public void surfaceCreated (Surfaceholder holder) {if (!isopencamera) return;
      try {Initcamera ();
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 
    @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {}
      @Override public void surfacedestroyed (Surfaceholder holder) {if (!isopencamera) return;
    Freecameraresource ();  }/** * Initialization camera * * @author Liuyinjun * @date 2015-2-5 * @throws ioexception/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 camera for vertical screen * * @author Liuyinjun * @date 2015-2-5/private void Setcameraparams () {if (
      Mcamera!= null) {Parameters params = mcamera.getparameters ();
      Params.set ("Orientation", "portrait");
    Mcamera.setparameters (params);
    /** * Release Camera resources * * @author Liuyinjun * @date 2015-2-5/private void Freecameraresource () {
      if (Mcamera!= null) {mcamera.setpreviewcallback (null);
      Mcamera.stoppreview ();
      Mcamera.lock ();
      Mcamera.release ();
    Mcamera = null; } private void Createrecorddir () {File Sampledir = new file (environment.getexternalstoragedirectory () + file.
    Separator + "im/video/");
    if (!sampledir.exists ()) {sampledir.mkdirs ();
    } File vecorddir = Sampledir; Create file try {mvecordfile = File.createtempfile ("Recording", ". mp4", vecorddir);//mp4 format logutils.i (mvecord
    File.getabsolutepath ());catch (IOException e) {}}/** * initialization * * @author Liuyinjun * @date 2015-2-5 * @throws ioexcep
    tion */private void Initrecord () throws IOException {Mmediarecorder = 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 MMe Diarecorder.setoutputformat (outputformat.mpeg_4);//Video output format mmediarecorder.setaudioencoder (AudioEncoder.AMR_NB); /audio Format mmediarecorder.setvideosize (mwidth, mheight);//Set Resolution://Mmediarecorder.setvideoframerate (16);//This I removed it, Feel nothing with mmediarecorder.setvideoencodingbitrate (1 * 1024 * 512)//Set frame frequency, then clear the Mmediarecorder.setorientationhint (90 )//Output rotate 90 degrees, keep the vertical screen recording mmediarecorder.setvideoencoder (VIDEOENCODER.MPEG_4_SP);//VideoRecording 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 * * @author Liuyinjun * @date 2015-2-5 * @param fileName * Video storage location * @par Am Onrecordfinishlistener * After a specified time the callback interface/public void record (final Onrecordfinishlistener Onrecordfinishlis
    Tener) {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 () {//TODO Auto-generAted method Stub 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 * * @author Liuyinjun * @date 2015-2-5/public void Stop () {Stoprecord ();
    Releaserecord ();
  Freecameraresource (); /** * Stop Recording * * @author Liuyinjun * @date 2015-2-5/public void Stoprecord () {MPROGRESSBAR.S
    Etprogress (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 ();
    /** * FREE Resources * * @author Liuyinjun * @date 2015-2-5/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;
  }/** * @return the Mvecordfile */public File Getmvecordfile () {return mvecordfile; /** * Recording Complete Callback interface * * @author liuyinjun * * @date 2015-2-5/public interface Onrecordfinishliste
  NER {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 (); }
  }
}

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>

Attrs.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" android:layout_width= "
     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>

The above mentioned is the entire content of this article, I hope you can enjoy.

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.