Android for video recording playback

Source: Internet
Author: User

for a similar small video feature, you can record a video and then play the video.

Video recording, using a custom control.

<span style= "FONT-SIZE:14PX;" >/** * Video Recording control * * @author Lip * * @date 2015-3-16 */public class Movierecorderview extends LinearLayout implements on    Errorlistener {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 start with camera private int mrecordmaxtime;/  /One shot maximum time private int mtimecount;//time count private file Mvecordfile = null;//file public Movierecorderview (Context    Context) {This (context, NULL);    } public Movierecorderview (context context, AttributeSet Attrs) {This (context, attrs, 0); } @TargetApi (Build.version_codes. Honeycomb) Public Movierecorderview (context context, AttributeSet attrs, int defstyle) {        Super (context, attrs, Defstyle);        mwidth=320;        mheight=240;        Isopencamera=true;         mrecordmaxtime=10;        Layoutinflater.from (context). Inflate (R.layout.moive_recorder_view, this);        Msurfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview);        Mprogressbar = (ProgressBar) Findviewbyid (R.id.progressbar);        Mprogressbar.setmax (mrecordmaxtime);//Set the maximum number of progress bars Msurfaceholder = Msurfaceview.getholder ();        Msurfaceholder.addcallback (New Customcallback ());    Msurfaceholder.settype (surfaceholder.surface_type_push_buffers); }/** * * @author liuyinjun * * @date 2015-2-5 * * Private class Customcallback implements Cal                lback {@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 (); }}/** * Initialize camera * * @author Lip * @date 2015-3-16 * @throws ioexception */Private VO        ID 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 to vertical screen * * @author lip * @datE 2015-3-16 */private void Setcameraparams () {if (Mcamera! = null) {Parameters params = Mcamer            A.getparameters ();            Params.set ("Orientation", "portrait");        Mcamera.setparameters (params); }}/** * Release camera resource * * @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/");        File Sampledir = new file (environment.getexternalstoragedirectory () + file.separator+ "recordvideo/");        File Sampledir = new file ("/video/");        if (!sampledir.exists ()) {sampledir.mkdirs ();        } File vecorddir = Sampledir; Create a file        try {mvecordfile = File.createtempfile ("Recording", ". mp4", vecorddir);//mp4 format//logutils.i            (Mvecordfile.getabsolutepath ());        LOG.D ("Path:", Mvecordfile.getabsolutepath ()); } catch (IOException e) {}}/** * Initialize * * @author lip * @date 2015-3-16 * @throws IOE        Xception */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 Mmediarecorder.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 took it off, it felt nothing to use mmediarecorder.setvideoencodingbitrate (1 * 1024 * 5 12)///Set the frame frequency, then clear the Mmediarecorder.setorientationhint (90);//output rotates 90 degrees, keep the vertical screen recording Mmediarecorder.setvideoencoder (V        IDEOENCODER.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 * * @author Liuyinjun * @date 2015-2-5//* @param filename//* Video storage location * @param Onrecordfinishlistener * Callback interface after the specified time */public void record (final Onrecordfinis Hlistener onrecordfinishlistener) {thIs.monrecordfinishlistener = Onrecordfinishlistener;        Createrecorddir ();            try {if (!isopencamera)//If the camera is not turned on, Initcamera () is turned on;            Initrecord ();            Mtimecount = 0;//Time counter re-assigned Mtimer = new Timer (); Mtimer.schedule (New TimerTask () {@Override public void run () {//TODO                    auto-generated method Stub mtimecount++;                        Mprogressbar.setprogress (Mtimecount);//Set the progress bar if (Mtimecount = = Mrecordmaxtime) {//to reach the 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 () {Mprog        Ressbar.setprogress (0);        if (Mtimer! = null) Mtimer.cancel ();            if (Mmediarecorder! = null) {//set does not collapse 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 Releaserecor            D () {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 completed callback interface * * @author Lip * * @date 2015-3-16 */public interface Onrecordfinishlis    tener {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 (); }}}</span>


Video playback:

<span style= "FONT-SIZE:14PX;"    >public class Mainactivity extends Actionbaractivity {private Movierecorderview movierv;    Private Button startbtn;    Private Button stopbtn;    Private Button playbtn;    Private Button pausebtn;    Private Surfaceview Playview;    Private MediaPlayer player;    int position; Public mainactivity () {} @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (SA        Vedinstancestate);        Setcontentview (R.layout.activity_main);        Initviews ();        Initevents ();    Init ();        } private void Init () {player=new MediaPlayer ();        playview= (Surfaceview) This.findviewbyid (R.ID.PLAY_SURFACEV);        Set the buffer Playview.getholder () that Surfaceview itself does not manage. SetType (surfaceholder.surface_type_push_buffers); Playview.getholder (). Addcallback (New Callback () {@Override public void surfacedestroyed (surfacehold ER holder) {} @Override PUBlic void surfacecreated (Surfaceholder holder) {if (position>0) {try {                        Start playing play ();                        and start playing player.seekto (position) directly from the specified position;                    position=0;            } catch (Exception e) {//Todo:handle Exception}}                                       } @Override public void surfacechanged (surfaceholder holder, int format, int width,    int height) {}});        } private void Initviews () {movierv= (Movierecorderview) Findviewbyid (R.ID.MOIVE_RV);        Record startbtn= (Button) Findviewbyid (R.ID.START_BTN);        Stopbtn= (Button) Findviewbyid (R.ID.STOP_BTN);        Play playbtn= (Button) Findviewbyid (R.ID.PLAY_BTN);    Pausebtn= (Button) Findviewbyid (R.ID.PAUSE_BTN); } private void Initevents () {//Start recording Startbtn.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (V                    Iew v) {Movierv.record (new Movierecorderview.onrecordfinishlistener () {@Override            public void Onrecordfinish () {}});        }        }); Stop Recording Stopbtn.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (            View v) {movierv.stop ();        }        }); Play recorded video Playbtn.setonclicklistener (new View.onclicklistener () {@Override public void oncli            CK (View v) {play ();        }        }); Pause Pausebtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (V               Iew v) {if (player.isplaying ()) {player.pause ();      } else         {Player.start ();    }            }        }); } @Override protected void OnPause () {//first determine if the IF (Player.isplaying ()) is being played {//If you are playing we will first save           This playback position position=player.getcurrentposition ();        Player.stop ();    } super.onpause ();            private void Play () {try {log.d ("Play:", "");            Player.reset ();            Player.setaudiostreamtype (Audiomanager.stream_music);            Set the video to be played String Path=movierv.getmvecordfile (). GetAbsolutePath ();            Player.setdatasource (path);            LOG.D ("Play:", Path);            Output the video image to Surfaceview Player.setdisplay (Playview.getholder ());            Player.prepare ();        Play Player.start (); } catch (Exception e) {//Todo:handle Exception}}}</span>
Layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "HTTP://SCHEMAS.A                Ndroid.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent " android:paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity _horizontal_margin "android:paddingtop=" @dimen/activity_vertical_margin "Android:paddingbott om= "@dimen/activity_vertical_margin" tools:context= ". Mainactivity "> <record.lip.com.videorecord.movierecorderview android:id=" @+id/moive_rv "Android:lay        Out_centerhorizontal= "true" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" >        </record.lip.com.videorecord.MovieRecorderView> <relativelayout android:id= "@+id/record_rl" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content"Android:layout_below=" @id/moive_rv "android:gravity=" center "android:layout_centerinparent=" true "&G        T <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro            Id:id= "@+id/start_btn" android:text= "Start"/> <button android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:id= "@+id/stop_btn" android:layout_torightof= "@id/start_btn" android:text= "Stop"/> </RelativeLayout> <surfaceview android:id= "@+i D/play_surfacev "android:layout_below=" @id/record_rl "android:layout_width=" 200DP "Android:layout_hei        ght= "200DP" android:layout_centerhorizontal= "true"/> <relativelayout android:id= "@+id/play_rl" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/play_s      Urfacev "  android:gravity= "Center" android:layout_centerinparent= "true" > <button android:layout_width= "wrap _content "android:layout_height=" wrap_content "android:id=" @+id/play_btn "android:text=" Play "/> & Lt Button android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:id= "@+id/paus E_btn "android:text=" pause "android:layout_torightof=" @id/play_btn "/> </relativelayout></rel Ativelayout>
Required System permissions:

    <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission Android:name= "Android.permission.CAMERA"/>    <uses-permission android:name= "android.permission.RECORD_ AUDIO "/>

The basic video recording function is possible.

: Android fake video recording playback

Android for video recording playback

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.