Android uses surfaceview+mediaplayer+ custom Mediacontroller to implement a custom video player

Source: Internet
Author: User

As follows:

(PS is supposed to give everyone to wear GIF dynamic diagram, but too big, unable to upload)

Feature implementation: Pause, play, fast forward, rewind, fullscreen, exit fullscreen, etc. basic functions

Realization of the idea:

Place a surfaceview in the main layout, place a mediaplayer in the Surfaceview, and customize a mediacontroller underneath it, but it's not called Mediacontroller, Using Pupupwindow to implement, put a few textview,button in the Pupupwindow layout, the most important to make our Seekbar control, create a timer when the user touches the screen, let it popupwindow display 5 Seconds of time , the concrete implementation can look at the code (the main program code a little more, patience to see AH)

Main layout Activity_main.xml file

<relativelayout 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 "    tools:context= ". Mainactivity ">    <surfaceview         android:layout_width=" match_parent "        android:layout_height=" 260DP "        android:id=" @+id/surfaceview_main "        />    <imageview        android:onclick=" Clickbutton        " Android:id= "@+id/imageview_main_play"        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:layout_alignparenttop=" true "        android:layout_centerhorizontal=" true "        android:layout_margintop= "100DP"        android:src= "@drawable/ic_launcher"/>  </RelativeLayout>

Layout of the Popupwindow.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:id=" @+id/bottom_layout "android:layout_width=" match_parent "android:layout_height=" 50DP "Android oid:gravity= "center" android:orientation= "horizontal" android:background= "@drawable/voip_toast_bg" Android:paddin gleft= "5DP" android:paddingright= "5DP" android:weightsum= "ten" > <imageview android:id= "@+id/imagevie W_play "android:layout_width=" 0DP "android:layout_height=" 30DP "android:layout_weight=" 1 "Android        oid:src= "@drawable/video_btn_on"/> <seekbar android:id= "@+id/seekbar" android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "5.0" android:max= "[Android:maxh]" eight= "5DP" android:minheight= "5DP" android:layout_marginleft= "5DP" android:progress= "0" Andro         id:thumboffset= "0DP"/>   <textview android:id= "@+id/textview_playtime" android:layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "1.3" android:gravity= "center" android:text= "00:00" Andro Id:textcolor= "@android: Color/white" android:textsize= "12sp"/> <textview android:id= "@+id/textv Iew_playtime "android:layout_width=" 0DP "android:layout_height=" Match_parent "android:layout_weight=" 0.2 "android:gravity=" center "android:text="/"android:textcolor=" @android: Color/white "Androi        D:textsize= "12SP"/> <textview android:id= "@+id/textview_totaltime" android:layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "1.3" android:gravity= "center" Android        oid:text= "00:00" android:textcolor= "@android: Color/white" android:textsize= "12sp"/> <imageview Android:id= "@+id/imaGeview_fullscreen "android:layout_width=" 0DP "android:layout_height=" 30DP "android:layout_weight=" 1 " android:src= "@drawable/video_full_screen"/></linearlayout>

  

Code in the main activity:

Package Com.amy.day43_03_surfaceviewmediaplayer;import Java.io.file;import Java.io.ioexception;import Java.text.simpledateformat;import java.util.date;import java.util.timer;import java.util.TimerTask;import android. R.integer;import Android.app.activity;import Android.app.alertdialog;import Android.content.BroadcastReceiver; Import Android.content.context;import Android.content.dialoginterface;import Android.content.intent;import Android.content.intentfilter;import Android.content.pm.activityinfo;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.os.Environment;import Android.os.handler;import Android.text.format.dateformat;import Android.util.log;import Android.view.Menu;import Android.view.motionevent;import Android.view.surfaceholder;import Android.view.surfaceholder.callback;import Android.view.surfaceview;imPort Android.view.view;import Android.view.view.onclicklistener;import Android.view.view.ontouchlistener;import Android.view.viewgroup.layoutparams;import Android.widget.imageview;import Android.widget.mediacontroller;import Android.widget.popupwindow;import Android.widget.seekbar;import Android.widget.SeekBar.OnSeekBarChangeListener; Import Android.widget.textview;public class Mainactivity extends Activity {private final static String TAG = "mainactivity ";p rivate Context mcontext = this;private Surfaceview Surfaceview = null;private Surfaceholder Surfaceholder = Null;privat   E MediaPlayer MediaPlayer = null;private ImageView imageview_main_show = null; Customizing the control bar and its controls private View controllerview;private Popupwindow popupwindow;private ImageView imageview_play;private ImageView imageview_fullscreen;private SeekBar seekbar;private TextView textview_playtime;private TextView textview_ Duration;private String filePath = null;private float densityratio = 1.0f; Density ratio coefficient (density ratio: pixels in one inch divided by weight) priVate Runnable r = new Runnable () {@Overridepublic void Run () {//Return to the main thread Showorhiddencontroller ();}}; Private Myvideobroadcastreceiver receiver = null;//Set Timer Private Timer timer = null;private final static int what = 0;priv Ate Handler Handler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (msg.what) {case What:if (m Ediaplayer! = null) {int currentplayer = mediaplayer.getcurrentposition (); if (Currentplayer > 0) { Mediaplayer.getcurrentposition (); Textview_playtime.settext (Formattime (Currentplayer));//Let seekbar also follow change int progress = (int) ((Currentplayer/(float) mediaplayer.getduration ()) *); seekbar.setprogress (progress);} else {textview_playtime.settext ("00:00"); seekbar.setprogress (0);}} break;default:break;}};};/ /Auto Hide custom Player control bar time private static final int hidden_time = savedinstancestate, @Overrideprotected void onCreate {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); InitMediaPlayer (); Initcontroller ();//DynamicRegistered Broadcast Recipient receiver = new Myvideobroadcastreceiver (); Registerreceiver (receiver, New Intentfilter ("com.amy.day43_03_ Surfaceviewmediaplayer "));} Private String Formattime (long time) {SimpleDateFormat formatter = new SimpleDateFormat ("Mm:ss"); return Formatter.format (new Date);} private void Initcontroller () {Controllerview = Getlayoutinflater (). Inflate (R.layout.popupwindow_mediacontroller, NULL);//Initialize Popopwindowpopupwindow = new Popupwindow (controllerview,layoutparams.match_parent, LAYOUTPARAMS.WRAP_ CONTENT, true); Imageview_play = (ImageView) Controllerview.findviewbyid (r.id.imageview_play); imageview_fullscreen = (ImageView) Controllerview.findviewbyid (r.id.imageview_fullscreen); SeekBar = (SeekBar) Controllerview.findviewbyid (r.id.seekbar); textview_playtime = (TextView) Controllerview.findviewbyid (r.id.textview_playtime); textView_ Duration = (TextView) Controllerview.findviewbyid (r.id.textview_totaltime); Seekbar.setonseekbarchangelistener (new Onseekbarchangelistener () {//= Finger drag seekbar complete,Finger leave screen will trigger the following method @overridepublic void Onstoptrackingtouch (SeekBar SeekBar) {//Let timer delay execution handler.postdelayed (R, Hidden_ time);} Method @overridepublic void Onstarttrackingtouch (SeekBar SeekBar) when the finger is dragging SeekBar while the finger does not leave the screen Let the timer cancel the timer handler.removecallbacks (r);} @Overridepublic void onprogresschanged (SeekBar SeekBar, int progress,boolean fromuser) {if (fromuser) {int playtime = Prog Ress * mediaplayer.getduration ()/100;mediaplayer.seekto (playtime);}}); /Click Play to determine whether to play or pause Imageview_play.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {if ( Imageview_main_show.getvisibility () = = view.visible) {imageview_main_show.setvisibility (View.GONE);} if (mediaplayer.isplaying ()) {mediaplayer.pause (); Imageview_play.setimageresource (R.drawable.video_btn_down);} else {mediaplayer.start (); Imageview_play.setimageresource (r.drawable.video_btn_on);}}); /implement full screen and exit full screen (the contents of the screen, not the screens of the portrait) Imageview_fullscreen.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {if (getRequestedorientation () = = Activityinfo.screen_orientation_landscape) {setrequestedorientation (ActivityInfo.SCREEN _orientation_portrait); Imageview_fullscreen.setimageresource (r.drawable.video_full_screen);// Reset the height and width of the Surfaceview surfaceview.getlayoutparams (). width = Layoutparams.match_parent;surfaceview.getlayoutparams (). Height = (int) (260 * densityratio);} else if (getrequestedorientation () = = activityinfo.screen_orientation_portrait) {setrequestedorientation ( Activityinfo.screen_orientation_landscape); Imageview_fullscreen.setimageresource (R.drawable.video_inner_screen ); Surfaceview.getlayoutparams (). Width = Layoutparams.match_parent;surfaceview.getlayoutparams (). Height = Layoutparams.match_parent;} Surfaceview.setlayoutparams (Surfaceview.getlayoutparams ());});} private void Showorhiddencontroller () {if (popupwindow.isshowing ()) {Popupwindow.dismiss ();} else {//convert DP to Pxint Controllerheightpixel = (int) (Densityratio *);p opupwindow.showasdropdown (surfaceview, 0,-controllerheightpixel);//Delay Execution handler.postdelayed (r, Hidden_time);}} private void Initmediaplayer () {FilePath = Environment.getexternalstoragepublicdirectory (environment.directory_ DOWNLOADS). GetAbsolutePath () + File.separator + "Myabc.mp4"; LOG.I ("==main==", "===========" + environment.getexternalstoragepublicdirectory (environment.directory_downloads). GetAbsolutePath ()); if (MediaPlayer = = null) {//1, create Mediaplay object mediaPlayer = new MediaPlayer (); Mediaplayer.reset (); try {Mediaplayer.setdatasource (FilePath); Mediaplayer.prepare ();//Mediaplayer.start (); mediaplayer.setlooping (false) ;} catch (IllegalStateException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}} Mediaplayer.setonpreparedlistener (New Onpreparedlistener () {@Overridepublic void onprepared (MediaPlayer MP) {// Indicates readiness to complete, set the total duration, use the time Formatting Tool//String duration = Mediaplayer.getduration (); Textview_duration.settext (Formattime ( Mediaplayer.getduration ()));//Initialize Timer timer = new timer (); Timer.schedule (new TimerTask () {@Overridepublic void run () {haNdler.sendemptymessage (what);}}, 0, 1000);}); Mediaplayer.setonerrorlistener (New Onerrorlistener () {@Overridepublic Boolean onError (MediaPlayer MP, int what, int Extra) {mp.reset (); return false;}}); Mediaplayer.setoncompletionlistener (New Oncompletionlistener () {@Overridepublic void oncompletion (MediaPlayer MP) {/ /Send broadcast, play next song Intent intent = new intent (); Intent.setaction ("Com.amy.day43_03_SurfaceViewMediaPlayer"); Sendbroadcast (intent);}});} private void Initview () {//TODO auto-generated Method stubdensityratio = Getresources (). Getdisplaymetrics (). density;// Represents getting the true density Imageview_main_show = (ImageView) Findviewbyid (r.id.imageview_main_play); Surfaceview = (Surfaceview) Findviewbyid (r.id.surfaceview_main); surfaceholder = Surfaceview.getholder (); Surfaceholder.addcallback (new Callback () {@Overridepublic void surfacedestroyed (Surfaceholder holder) {//TODO auto-generated method Stubif ( MediaPlayer! = null) {mediaplayer.stop (); Mediaplayer.release ();}} @Overridepublic void surfacecreated (SurfaceHolder Holder) {//TODO auto-generated method stubif (MediaPlayer! = null) {Mediaplayer.setdisplay (Surfaceholder);//Medi Aplayer.start ();}}  @Overridepublic void Surfacechanged (surfaceholder holder, int format,int width, int height) {//TODO auto-generated method Surfaceview.setontouchlistener (New Ontouchlistener () {@Overridepublic A Boolean OnTouch (View V, Motionevent event) {//indicates that the control bar switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:showOrHiddenController is displayed at the instant of the Click (); break;default:break;} return true;});} /** * Setting the control's listener event * * @param v */public void Clickbutton (View v) {switch (V.getid ()) {case R.id.imageview_main_play:imagevi Ew_main_show.setvisibility (View.gone); Mediaplayer.start (); break;default:break;}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overrideprotected void OnDestroy () {//TODO auto-generated method stubsuper.oNdestroy (); Unregisterreceiver (receiver); Timer.cancel (); if (mediaPlayer! = null) {mediaplayer.release (); MediaPlayer = null;} Handler.removecallbacksandmessages (null);} Class Myvideobroadcastreceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent {if (Intent.getaction (). Equals ("Com.amy.day43_03_SurfaceViewMediaPlayer")) {Alertdialog.builder Builder = new Alertdialog.builder (context); Builder.seticon (R.drawable.ic_launcher). Settitle ("hint"). Setmessage ("video playback is complete, play"). Setnegativebutton ("Cancel", null). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog,int which) {mediaplayer.reset (); try {mediaplayer.setdatasource (FilePath); Mediaplayer.prepare ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Mediaplayer.setlooping (false); Mediaplayer.start ();}}). Show ();}}}}

  

Android uses surfaceview+mediaplayer+ custom Mediacontroller to implement a custom video player

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.