The realization method of MediaPlayer playing network video by Android _android

Source: Internet
Author: User
Tags prepare

The front explained the MediaPlayer playback network audio, mainly introduced MediaPlayer about the network audio buffering and the progress bar control method, this article again explains the MediaPlayer to play the network video the method. Playing network video than playing the network audio requires a Surfaceview only, in the already familiar with the MediaPlayer play network audio, I believe that this article on the play network video can quickly grasp.

Let's take a look at this program to run the screenshot as follows:

This program's video from Http://daily3gp.com, you can replace the video link in the program, try other videos.

Main.xml source code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <framelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:layout_height=" Fill_parent "android:layout_width=" fill_parent "> <surfaceview android:id=" @+
 Id/surfaceview1 "android:layout_height=" fill_parent "android:layout_width=" Fill_parent "></SurfaceView> <linearlayout android:layout_height= "wrap_content" android:layout_width= "Fill_parent" Bottom "android:orientation=" vertical "> <linearlayout android:orientation=" Horizontal "Android:layout_" Gravity= "Center_horizontal" android:layout_margintop= "4.0dip" android:layout_height= "Wrap_content" android:layout _width= "Wrap_content" > <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:id= "@+id/btnplayurl" android:text= "Play network Video" ></Button> <button android:layout_height= "WRAP_" Content "android:id=" @+id/btnpause "android:text=" pause "android:layout_width=" 80dip "&GT;&Lt;/button> <button android:layout_height= "wrap_content" android:layout_width= "80dip" android:text= "Stop" Android:id= "@+id/btnstop" ></Button> </LinearLayout> <linearlayout android:orientation= " Horizontal "android:layout_width=" Fill_parent "android:layout_height=" Wrap_content "android:layout_marginBottom=" 20dip "> <seekbar android:paddingright=" 10dip "android:layout_gravity=" center_vertical "android:paddingleft="
  10dip "android:layout_weight=" 1.0 "android:layout_height=" wrap_content "android:layout_width=" Wrap_content "
Android:id= "@+id/skbprogress" android:max= "></SeekBar> </LinearLayout> </LinearLayout>"

 </FrameLayout>

Player.java is the core of this paper, Player.java realizes "progress bar Update", "Data buffer", "Surfaceholder life cycle" and so on, in which "Surfaceholder life cycle" is the biggest difference between video and audio playback, Some resources can be created/freed through surfacecreated (), surfacedestroyed (), surfacechanged (). Here's a place to pay attention to:

Videowidth = Mediaplayer.getvideowidth ();
Videoheight = Mediaplayer.getvideoheight ();
if (videoheight!= 0 && videowidth!= 0) {
 arg0.start ();
}

Some videos are not played by the Android player and cannot be played videoheight=0,videowidth=0 to determine whether or not to play the video.

Player.java source code is as follows:

Package com.videoplayer;
Import java.io.IOException;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import Android.media.AudioManager;
Import Android.media.MediaPlayer;
Import Android.media.MediaPlayer.OnBufferingUpdateListener;
Import Android.media.MediaPlayer.OnCompletionListener;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.util.Log;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceView;
Import Android.widget.SeekBar;
 public class Player implements Onbufferingupdatelistener, Oncompletionlistener, Mediaplayer.onpreparedlistener,
 surfaceholder.callback {private int videowidth;
 private int videoheight;
 Public MediaPlayer MediaPlayer;
 Private Surfaceholder Surfaceholder;
 Private SeekBar skbprogress;
 Private timer mtimer=new timer ();
 Public Player (Surfaceview Surfaceview,seekbar skbprogress) {this.skbprogress=skbprogress;
 Surfaceholder=surfaceview.getholder ();
 Surfaceholder.addcallback (this); Surfaceholder.settype (SURFACEHOLDER.SUrface_type_push_buffers);
 Mtimer.schedule (mtimertask, 0, 1000); /******************************************************* * Updates the progress bar through timers and handler **********************************
  /TimerTask Mtimertask = new TimerTask () {@Override public void run () {if (mediaplayer==null)
  Return
  if (mediaplayer.isplaying () && skbprogress.ispressed () = False) {handleprogress.sendemptymessage (0);
 }
 }
 }; Handler handleprogress = new Handler () {public void Handlemessage (msg) {int position = Mediaplayer.getcurrent
  Position ();
  
  int duration = Mediaplayer.getduration ();
  if (Duration > 0) {Long pos = Skbprogress.getmax () * position/duration;
  Skbprogress.setprogress ((int) POS);
 }
 };
 };
 public void Play () {Mediaplayer.start ();
  public void Playurl (String videourl) {try {mediaplayer.reset ();
  Mediaplayer.setdatasource (Videourl); Mediaplayer.prepare ();//prepare//mediaplayer.start () after the automatic playback;
 catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();
 catch (IllegalStateException e) {//TODO auto-generated catch block E.printstacktrace ();
 catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 } public void Pause () {mediaplayer.pause ();
      public void Stop () {if (MediaPlayer!= null) {mediaplayer.stop (); 
      Mediaplayer.release (); 
    MediaPlayer = null; @Override public void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {log.e ("MediaPlayer", "su
 Rface changed ");
  @Override public void surfacecreated (Surfaceholder arg0) {try {mediaPlayer = new MediaPlayer ();
  Mediaplayer.setdisplay (Surfaceholder);
  Mediaplayer.setaudiostreamtype (Audiomanager.stream_music);
  Mediaplayer.setonbufferingupdatelistener (this);
 Mediaplayer.setonpreparedlistener (this); catch (Exception e) {log.e ("MediaPlayer", "ERRor ", e);
 } log.e ("MediaPlayer", "surface created");
 @Override public void surfacedestroyed (Surfaceholder arg0) {log.e ("MediaPlayer", "surface destroyed"); @Override/** * played via onprepared/public void onprepared (MediaPlayer arg0) {videowidth = Mediaplayer.getvideowidt
 H ();
 Videoheight = Mediaplayer.getvideoheight ();
 if (videoheight!= 0 && videowidth!= 0) {Arg0.start ();
 } log.e ("MediaPlayer", "onprepared");  @Override public void Oncompletion (MediaPlayer arg0) {//TODO auto-generated a stub} @Override public void
 Onbufferingupdate (MediaPlayer arg0, int bufferingprogress) {skbprogress.setsecondaryprogress (bufferingprogress);
 int Currentprogress=skbprogress.getmax () *mediaplayer.getcurrentposition ()/mediaplayer.getduration ();
 LOG.E (currentprogress+ "% play", bufferingprogress + "% buffer");

 }
}

Test_videoplayer.java is the main program that calls the player class, where the key part is seekbarchangeevent the Seekbar drag event:seekbar Progress is 0~ The number within the Seekbar.getmax (), and the Mediaplayer.seekto () is the number of 0~mediaplayer.getduration (), so the parameter of Mediaplayer.seekto () is ( Progress/seekbar.getmax ()) *mediaplayer.getduration ().

Test_videoplayer.java source code is as follows:

Package com.videoplayer;
Import android.app.Activity;
Import Android.content.pm.ActivityInfo;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.SurfaceView;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.SeekBar;
 public class Test_videoplayer extends activity {private Surfaceview Surfaceview;
 Private Button Btnpause, Btnplayurl, btnstop;
 Private SeekBar skbprogress;
 Private player player; /** called the activity is a.
 * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main);
 Setrequestedorientation (Activityinfo.screen_orientation_landscape);

 Surfaceview = (Surfaceview) This.findviewbyid (R.ID.SURFACEVIEW1);
 Btnplayurl = (Button) This.findviewbyid (R.id.btnplayurl);

 Btnplayurl.setonclicklistener (New Clickevent ());
Btnpause = (Button) This.findviewbyid (r.id.btnpause); Btnpause.setonclicklistener (New Clickevent ());
 Btnstop = (Button) This.findviewbyid (r.id.btnstop);

 Btnstop.setonclicklistener (New Clickevent ());
 Skbprogress = (SeekBar) This.findviewbyid (r.id.skbprogress);
 Skbprogress.setonseekbarchangelistener (New Seekbarchangeevent ());
 Player = new player (Surfaceview, skbprogress);
  Class Clickevent implements Onclicklistener {@Override public void OnClick (View arg0) {if (arg0 = = Btnpause) {
  Player.pause ();
  else if (arg0 = = Btnplayurl) {String url= "http://daily3gp.com/vids/family_guy_penis_car.3gp";
  Player.playurl (URL);
  else if (arg0 = = btnstop) {player.stop ();
 Class Seekbarchangeevent implements Seekbar.onseekbarchangelistener {int progress; @Override public void onprogresschanged (SeekBar SeekBar, int progress, Boolean Fromuser) {//originally (progress/seekbar.ge TMax ()) *player.mediaplayer.getduration () this.progress = progress * player.mediaPlayer.getDuration ()/Seekbar.getmax
 (); } @Override Public void Onstarttrackingtouch (SeekBar SeekBar) {} @Override public void Onstoptrackingtouch (SeekBar SeekBar) {//
 The Seekto () parameter is relative to the time of the film, rather than the digital player.mediaPlayer.seekTo (progress) relative to the Seekbar.getmax ();

 }
 }
}

Interested readers can test the example code of this article by themselves, I believe that for everyone to carry out the development of the Android program has a certain reference role.

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.