Android custom Video Player

Source: Internet
Author: User

I found a lot of related information on the Internet and felt I didn't want it. I decided to write it myself.

Source code has been put in the resource library, welcome to download: http://download.csdn.net/detail/luozhi3527/5353003

The program uses surface + mediaplayer to customize the console. Can Play local and online videos.

The main implementation code is as follows:

Package COM. xluo. mediaplayertest; import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. app. progressdialog; import android. media. audiomanager; import android. media. mediaplayer; import android. media. mediaplayer. oncompletionlistener; import android. media. mediaplayer. onerrorlistener; import android. media. mediaplayer. oninfolistener; import android. media. mediaplayer. onpre Paredlistener; import android. media. mediaplayer. onseekcompletelistener; import android. media. mediaplayer. onvideosizechangedlistener; import android.net. uri; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. display; import android. view. keyevent; import android. view. surfaceholder; import android. view. surfaceview; import android. view. vie W; import android. view. windowmanager; import android. widget. imagebutton; import android. widget. linearlayout; import android. widget. seekbar; import android. widget. textview; import android. widget. toast; import android. widget. seekbar. onseekbarchangelistener; public class testvideoplayer extends activity implements oncompletionlistener, onerrorlistener, oninfolistener, onpreparedlistener, onseekcompletelistener, O Includeosizechangedlistener, surfaceholder. callback {public static final string tag = "testvideoplayer"; private Boolean isexit = false; private int currentmusicposition; // current volume string url = NULL; private URI; private string name; private imagebutton playbtn = NULL; // play and pause private textview playtime = NULL; // playback time private textview durationtime = NULL; // total time private textview videoname = NULL; private seekbar Seekbar = NULL; // progress Private seekbar soundbar = NULL; // volume adjustment private handler = new handler () {public void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. what) {Case 1: If (mediaplayer! = NULL) currentposition = mediaplayer. getcurrentposition (); seekbar. setprogress (currentposition); playtime. settext (totime (currentposition); handler. sendemptymessage (1); break; default: Break ;}}; // used for the progress bar private int currentposition; // The current playback position private progressdialog dialog; // load the wait box private audiomanager maudiomanager = NULL; private view video_contrlbar, titlebar; private Boolean iscontrolbarshow = true; display cur Preview display; surfaceview; surfaceholder; mediaplayer; // mediaplayer is used to play video int scurrentposition; // volume timer showcontroller = new timer (); timertask; private handler fhandler = new handler () {public void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. what) {Case 1: video_contrlbar.setvisibility (view. gone); titlebar. setvisibility (view. GON E); iscontrolbarshow = false; break; default: Break ;}}; // used for console explicit hidden Boolean readytoplayer = false; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); getwindow (). setflags (windowmanager. layoutparams. flag_keep_screen_on, windowmanager. layoutparams. flag_keep_screen_on); // you can specify getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layou Tparams. flag_fullscreen); // set setcontentview (R. layout. activity_main); name = "Sunday"; url = "/sdcard/sunny_night.mp4"; // logs available for both network and local videos. D (TAG, "url:" + URL); dialog = new progressdialog (this); // set to wait for the dialog. setmessage ("loading... "); dialog. show (); // console video_contrlbar = (View) findviewbyid (R. id. video_contrlbar); titlebar = (View) findviewbyid (R. id. video_titlebar); showcontrolbar ();/* time */playtime = (textview) Findviewbyid (R. id. video_playtime); // The played time durationtime = (textview) findviewbyid (R. id. video_duration); // total time videoname = (textview) findviewbyid (R. id. play_movie_name); videoname. settext (name);/* set the play, pause, and stop buttons */playbtn = (imagebutton) findviewbyid (R. id. video_playbtn); // start playbtn. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view v) {If (mediaplayer. isplaying () {pause (); PLA Ybtn. setbackgroundresource (R. drawable. video_play_selector);} else {play (); playbtn. setbackgroundresource (R. drawable. video_pause_selector) ;}}); // progress bar seekbar = (seekbar) findviewbyid (R. id. video_seekbar); seekbar. listener (New onseekbarchangelistener () {@ overridepublic void onstoptrackingtouch (seekbar) {}@ overridepublic void onstarttrackingtouch (seekbar) {}@ overridepublic Void onprogresschanged (seekbar, int progress, Boolean fromuser) {If (fromuser) mediaplayer. seekto (Progress) ;}});/* volume control bar */soundbar = (seekbar) findviewbyid (R. id. video_sound); soundbar. listener (New onseekbarchangelistener () {@ overridepublic void onstoptrackingtouch (seekbar) {// todo auto-generated method stub} @ overridepublic void onstarttrackingtouch (seekbar ){/ /Todo auto-generated method stub} @ overridepublic void onprogresschanged (seekbar, int progress, Boolean fromuser) {// todo auto-generated method stubif (fromuser) {int scurrentposition = soundbar. getprogress (); maudiomanager. setstreamvolume (audiomanager. stream_music, scurrentposition, 0) ;}}); surfaceview = (surfaceview) findviewbyid (R. id. surfaceview); surfaceholder = surfaceview. getholder (); Surfaceholder. addcallback (this); surfaceholder. settype (surfaceholder. surface_type_push_buffers); surfaceview. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubshowcontrolbar (); // call up the console when you click the screen ;}}); setup (); currentdisplay = getwindowmanager (). getdefadisplay display ();} private void showcontrolbar () {// video_contrlbar.setvisibili of the console Ty (view. Visible); titlebar. setvisibility (view. Visible); iscontrolbarshow = true; If (timertask! = NULL) {timertask. cancel ();} timertask = new timertask () {@ override public void run () {// todo auto-generated method stub if (iscontrolbarshow) {message MSG = fhandler. obtainmessage (1); fhandler. sendmessage (MSG) ;}}; showcontroller. schedule (timertask, 5000); // hide} runnable contrlshow = new runnable () {@ overridepublic void run () {// todo auto-generated method stubvideo_contrlbar.setvisibilit Y (view. gone); titlebar. setvisibility (view. gone); iscontrolbarshow = false; fhandler. postdelayed (contrlshow, 5000) ;};@ override public void surfacechanged (surfaceholder holder, int format, int width, int height) {} private void loadclip () {If (mediaplayer! = NULL) {mediaplayer. reset (); mediaplayer. release (); mediaplayer = NULL;} mediaplayer = new mediaplayer (); // create a mediaplayer. setoncompletionlistener (this); mediaplayer. setonerrorlistener (this); mediaplayer. setonpreparedlistener (this); mediaplayer. setonseekcompletelistener (this); mediaplayer. setonvideosizechangedlistener (this); // listentity entity = dbdao. find (position); // log. D (TAG, "list entit Y object: "+ entity); // string url = entity. geturl (); log. D (TAG, "url:" + URL); uri = Uri. parse (URL); log. D (TAG, "Media URL:" + URL); // URI = Uri. withappendedpath (mediastore. audio. media. external_content_uri, // "" + POS); try {mediaplayer. setdatasource (this, Uri);} catch (exception e) {e. printstacktrace () ;}} private void setup () {loadclip (); try {mediaplayer. prepare (); mediaplayer. setonpreparedlis Tener (New onpreparedlistener () {@ override public void onprepared (final mediaplayer MP) {seekbar. setmax (MP. getduration (); // sets the maximum value of the playback progress bar handler. sendemptymessage (1); // sends a message to handler to start the playtime of the playback progress bar. settext (totime (MP. getcurrentposition (); // initialize the playback time durationtime. settext (totime (MP. getduration (); // sets the time MP. seekto (currentposition); // initialize the mediaplayer playback position/* obtain the maximum volume */maudiomanager = (audiomanager) testvideo Player. this. getsystemservice (testvideoplayer. this. audio_service); int maxsound = maudiomanager. getstreammaxvolume (audiomanager. stream_music);/* Get the current volume */INT currentsound = maudiomanager. getstreamvolume (audiomanager. stream_music); soundbar. setmax (maxsound); soundbar. setprogress (currentsound) ;}});} catch (exception e) {e. printstacktrace () ;}} private void play () {log. D (TAG, "cancel dialog:" + DIALOG);/* set the video size */INT tmpwidth = currentdisplay. getheight (); int tmpheight = currentdisplay. getwidth (); surfaceview. setlayoutparams (New linearlayout. layoutparams (tmpheight, tmpwidth * 3/4); If (dialog! = NULL) {dialog. dismiss ();} mediaplayer. start (); playbtn. setbackgroundresource (R. drawable. video_pause_selector);} private void pause () {mediaplayer. pause () ;}public string totime (INT time) {time/= 1000; int minute = Time/60; int hour = minute/60; int second = time % 60; minute % = 60; return string. format ("% 02d: % 02d: % 02d", hour, minute, second) ;}@ override public void surfacecreated (Surface Holder) {log. D (TAG, "surafce created"); mediaplayer. setdisplay (surfaceholder); // if there is no sentence, only the sound will be played ();} @ override public void surfacedestroyed (surfaceholder holder) {// The playback ends when the surface is destroyed to prevent the image from being played even when the home key is pressed. If (mediaplayer! = NULL) {mediaplayer. reset (); mediaplayer. release (); mediaplayer = NULL;} finish () ;}@ override public void onvideosizechanged (mediaplayer arg0, int arg1, int arg2) {}@ override public void onseekcomplete (mediaplayer MP) {}@ override public void onprepared (mediaplayer MP) {}@ override public Boolean oninfo (mediaplayer arg0, int whatinfo, int extra) {return false ;}@ override public Boolean on Error (mediaplayer arg0, int arg1, int arg2) {return false ;}@ override public void oncompletion (mediaplayer arg0) {// automatically exit finish () after playing ();} public Boolean onkeydown (INT keycode, keyevent event) {Switch (keycode) {Case keyevent. keycode_back: exitby2click (); break; Case keyevent. keycode_volume_down: // volume key control. Call up the console log. D (TAG, "To pressed voice down"); showcontrolbar (); currentmusicposition = soundba R. getprogress (); currentmusicposition --; maudiomanager. setstreamvolume (audiomanager. stream_music, currentmusicposition, 0); soundbar. setprogress (currentmusicposition); break; Case keyevent. keycode_volume_up: log. D (TAG, "To pressed voice up"); showcontrolbar (); currentmusicposition = soundbar. getprogress (); currentmusicposition ++; maudiomanager. setstreamvolume (audiomanager. stream_music, currentmusic Position, 0); soundbar. setprogress (currentmusicposition); break; default: Super. onkeydown (keycode, event);} return true;} private void exitby2click () {timer texit = NULL; If (isexit = false) {isexit = true; // prepare to exit toast. maketext (this, "Play again after one click", toast. length_short ). show (); texit = new timer (); texit. schedule (New timertask () {@ override public void run () {isexit = false; // cancel logout}, 2000 ); // If the return key is not pressed within 2 seconds, start the timer to cancel the task just executed} else {If (mediaplayer! = NULL) {mediaplayer. Release (); mediaplayer. Reset (); mediaplayer = NULL;} finish ();}}}

The main code is annotated and there is no need to explain it again.

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.