Code for Android video playback

Source: Internet
Author: User

Local video playback, including play, pause, continue, etc., and show the progress of playback. The effect is as follows:
1.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:orientation= "vertical" tools:context= "com.zhang.videoplay.MainActivity" > <linearlay Out android:id= "@+id/line" android:layout_width= "match_parent" android:layout_height= "40DP" an        Droid:layout_margin= "10DP" android:orientation= "horizontal" > <button android:id= "@+id/playstart"        Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:gravity= "center" android:text= "Play"/> <button android:id= "@+id/pause" android:layout_width= "Wrap_cont         Ent "android:layout_height=" wrap_content "android:gravity=" center "android:text=" Pause "/> <button anDroid:id= "@+id/rebroadcast" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:gravity= "center" android:text= "replay"/> <button android:id= "@+id/plays Top "android:layout_width=" Wrap_content "android:layout_height=" Wrap_content "Android:gra vity= "center" android:text= "Stop"/> </LinearLayout> <surfaceview android:id= "@+id/surfac        Eview "android:layout_width=" 300DP "android:layout_height=" 300DP "android:layout_margin=" 20DP " /> <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" a ndroid:orientation= "Horizontal" > <textview android:id= "@+id/startime" Android:layout_wi            Dth= "Wrap_content" android:layout_height= "wrap_content" android:layout_marginleft= "10DP" android:gravity= "Center"            android:text= "00:00"/> <seekbar android:id= "@+id/seekbar" Android:layout_ height= "Wrap_content" android:layout_width= "Match_parent" android:layout_weight= "6"/> < TextView android:id= "@+id/sumtime" android:layout_width= "wrap_content" android:layout_height= "Wrap_co    Ntent "android:layout_marginleft=" 10DP "android:gravity=" center "android:text=" Hello "/> </LinearLayout></LinearLayout>

2.mainactivity.java
Package Com.zhang.videoplay;import Android.media.audiomanager;import Android.media.mediaplayer;import Android.media.mediaplayer.oncompletionlistener;import Android.media.mediaplayer.onerrorlistener;import Android.media.mediaplayer.onpreparedlistener;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.util.log;import Android.view.surfaceholder;import Android.view.surfaceholder.callback;import Android.view.surfaceview;import Android.view.view;import Android.widget.button;import Android.widget.seekbar;import Android.widget.seekbar.onseekbarchangelistener;import Android.widget.textview;import Android.widget.toast;import Java.io.file;import Java.text.SimpleDateFormat;import Java.util.date;public class Mainactivity extends Appcompatactivity implements View.onclicklistener {private Button pla    Start, pause, playstop, rebroadcast;    Private Surfaceview Surfaceview;    Private SeekBar SeekBar;    Private MediaPlayer MediaPlayer; private int Currentposition = 0;    Private Boolean isplaying;    Private TextView Starttime,sumtime;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();        Add callback Surfaceview.getholder () to Surfaceholder. Addcallback (callback); Set SURFACE not to maintain its own buffer, but wait for the screen's rendering engine to push the content to the interface Surfaceview.getholder (). SetType (Surfaceholder.surface_type_push_        buffers);    Add a progress Change event Seekbar.setonseekbarchangelistener for the progress bar;        } private void Initview () {Plastart = (Button) Findviewbyid (R.id.playstart);        Plastart.setonclicklistener (this);        Pause = (Button) Findviewbyid (r.id.pause);        Pause.setonclicklistener (this);        Playstop = (Button) Findviewbyid (r.id.playstop);        Playstop.setonclicklistener (this);        rebroadcast = (Button) Findviewbyid (r.id.rebroadcast);        Rebroadcast.setonclicklistener (this); Sumtime= (TextView) finDviewbyid (R.id.sumtime);        Starttime= (TextView) Findviewbyid (r.id.startime);        Surfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview);    SeekBar = (SeekBar) Findviewbyid (R.id.seekbar);                } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.playstart://start                Play (0);                Plastart.setenabled (FALSE);            Break                Case r.id.playstop://stopping stop ();            Break                Case r.id.rebroadcast://Replay Replay ();            Break                Case r.id.pause://pauses pause ();        Break }}//Add a Callback object to listen for changes to Surfaceview private Callback Callback = new Callback () {//Surfaceholder when modified Callback @Override public void surfacedestroyed (Surfaceholder holder) {log.i ("info", "Surfaceholder pin            Destruction "); When destroying Surfaceholder, record the current playback position and stop playing if (mediaPlayer! = null && Mediaplayer.isplaying ()) {currentposition = Mediaplayer.getcurrentposition ();            Mediaplayer.stop ();            }}//surfaceview triggered @Override public void surfacecreated (Surfaceholder holder) {            LOG.I ("info", "Surfaceholder is created"); if (currentposition > 0) {//create Surfaceholder, if there is a position last played, play played at the last playback position (CURRENTPO                Sition);            currentposition = 0;  }}//surfaceview triggers @Override public void surfacechanged (surfaceholder holder, int format,        int width, int height) {log.i ("info", "Surfaceholder size Changed");    }    }; Private Onseekbarchangelistener change = new Onseekbarchangelistener () {@Override public void Onstoptrackin Gtouch (SeekBar SeekBar) {/////Get the tick of the current progress bar when the progress bar stops modifying int progress = Seekbar.getprogre            SS ();if (MediaPlayer! = null && mediaplayer.isplaying ()) {//sets the current playing position Mediaplayer.seekt            O (progress); }} @Override public void Onstarttrackingtouch (SeekBar SeekBar) {} @Override PU            Blic void onprogresschanged (SeekBar SeekBar, int progress, Boolean fromuser) {            LOG.I ("info", "onstoptrackingtouch--" +progress);        Shifttime (starttime,progress);    }    }; /** * Start playing * * @param msec Playback Initial position */protected void play (final int msec) {//Get video file address St        Ring Path = "/storage/emulated/0/download/video.mp4";        File File = new file (path);            if (!file.exists ()) {Toast.maketext (this, "Video file path error", Toast.length_long). Show ();        Return            } try {mediaPlayer = new MediaPlayer ();            Mediaplayer.setaudiostreamtype (Audiomanager.stream_music);         Set the video source for playback   LOG.I ("info", "1111111" + File.getabsolutepath ());            Mediaplayer.setdatasource (File.getabsolutepath ());            Set the Surfaceholder of the display video, specify the video output to Surfaceview above Mediaplayer.setdisplay (Surfaceview.getholder ());            LOG.I ("Info", "Start loading");            Mediaplayer.prepareasync (); Mediaplayer.setonpreparedlistener (New Onpreparedlistener () {@Override public void Onprepare                    D (MediaPlayer MP) {log.i ("info", "load Complete");                    Mediaplayer.start ();                    Play Mediaplayer.seekto (msec) in the initial position;                    Set the maximum progress of the progress bar to the maximum playback duration of the video stream Seekbar.setmax (Mediaplayer.getduration ());                    LOG.I ("info", "2222222222-----" +mediaplayer.getduration ());                    Convert scale to TIME Mm:ss Shifttime (Sumtime,mediaplayer.getduration ()); Start thread, update the progress bar's scale new thread () {@OverRide public void Run () {try {isplaying                                = true;                                            while (isplaying) {int current = MediaPlayer                                    . GetCurrentPosition ();                                    Seekbar.setprogress (current);                                Sleep (1000);                            }} catch (Exception e) {e.printstacktrace ();                   }}}.start ();                Set the Stop button to non-clickable playstop.setenabled (false);            }            }); Mediaplayer.setoncompletionlistener (New Oncompletionlistener () {@Override public void oncom             Pletion (MediaPlayer MP) {//callback playstop.setenabled (TRUE) after playback is complete;   }            }); Mediaplayer.setonerrorlistener (New Onerrorlistener () {@Override public boolean onError (Medi                    Aplayer MP, int what, int extra) {//Error replay LOG.I ("info", "OnError---" +what);                    Play (0);                    IsPlaying = false;                return false;        }            });        } catch (Exception e) {e.printstacktrace (); }}/** * re-start playback */protected void Replay () {if (MediaPlayer! = null&& Mediaplayer.isplay            ing ()) {mediaplayer.seekto (0);            Toast.maketext (This, "Replay", Toast.length_long). Show ();            Pause.settext ("pause");        Return        } play (0);    IsPlaying = false;            }/** * Pauses or continues */protected void pause () {if (Pause.gettext (). toString (). Trim (). Equals ("continue")) {            Pause.settext ("pause");            Mediaplayer.start (); ToAst.maketext (This, "continue playing", Toast.length_short). Show ();        Return            } if (MediaPlayer! = null && mediaplayer.isplaying ()) {mediaplayer.pause ();            Pause.settext ("continue");        Toast.maketext (This, "Pause playback", Toast.length_short). Show (); }}/** * Stop playing */protected void Stop () {if (MediaPlayer! = null && mediaplayer.isplaying            ()) {mediaplayer.stop ();            Mediaplayer.release ();            MediaPlayer = null;            Playstop.setenabled (TRUE);        IsPlaying = false;        }}//Convert ticks to time private void Shifttime (TextView view,int times) {Date date = new Date ();        SimpleDateFormat SDF = new SimpleDateFormat ("Mm:ss");        Date.settime (time);        String str = sdf.format (date);        LOG.I ("info", "33333333-----" +str);    View.settext (str); }}



3. Permission to join
<!--write external storage that is SDcard permissions--    <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/ >    <!--turn off SDcard permissions--    <uses-permission android:name= "android.permission.MOUNT_UNMOUNT_ Filesystems "/>





Code for Android video playback

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.