Android improved MediaPlayer Playback Network audio Method _android

Source: Internet
Author: User
Tags prepare

Previous articles have introduced the basic usage of MediaPlayer, and here is a more in-depth explanation of MediaPlayer's online playback function. This paper mainly realizes the function of MediaPlayer playing audio online, because the online video playback is more complicated than the online audio playback, it introduces the realization of the online audio playback, which can help us to get a deeper understanding of MediaPlayer's online playback function.

Let's take a look at the results of this program running as shown in the following illustration:

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 "> <linearlayout android: layout_height= "Wrap_content" android:layout_width= "fill_parent" android:orientation= "vertical" android:layout_ gravity= "Top" > <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 Audio" ></Button> <button android:layout_height= "wrap_content" android:id= "@+id/" Btnpause "android:text=" pause "android:layout_width=" 80dip "></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 implements "progress bar Update", "Data buffering" and other functions, although not very complex function, but it is very useful function.

Player.java source code is as follows:

Package com.musicplayer;
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.widget.SeekBar;
 public class Player implements Onbufferingupdatelistener, Oncompletionlistener, mediaplayer.onpreparedlistener{
 Public MediaPlayer MediaPlayer;
 Private SeekBar skbprogress;
 Private timer mtimer=new timer ();
 Public Player (SeekBar skbprogress) {this.skbprogress=skbprogress;
  try {mediaPlayer = new MediaPlayer ();
  Mediaplayer.setaudiostreamtype (Audiomanager.stream_music);
  Mediaplayer.setonbufferingupdatelistener (this);
 Mediaplayer.setonpreparedlistener (this);
 catch (Exception e) {log.e ("MediaPlayer", "error", e);
 } mtimer.schedule (Mtimertask, 0, 1000); }
 /**************** Update progress bar via timer 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.getcurren
  Tposition ();
  
  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 automatically play//mediaplayer.start (); catch (IllegalArgumentException e) {//TODOAuto-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/** * onprepared play/public void onprepared (MediaPlayer arg0) {Arg0.start ();
 LOG.E ("MediaPlayer", "onprepared");
 @Override public void Oncompletion (MediaPlayer arg0) {log.e ("MediaPlayer", "oncompletion"); @Override public void Onbufferingupdate (MediaPlayer arg0, int bufferingprogress) {skbprogress.setsecondaryprogress (b
 ufferingprogress);
 int Currentprogress=skbprogress.getmax () *mediaplayer.getcurrentposition ()/mediaplayer.getduration ();
 LOG.E (currentprogress+ "% play", bufferingprogress + "% buffer");

 }
}

Test_musicplayer.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 ()) *player.mediaplayer.getduration ().

Test_musicplayer.java source code is as follows:

Package com.musicplayer;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.SeekBar;
 public class Test_musicplayer extends activity {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);
 This.settitle ("Online music playback---hellogv writing");
 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 (skbprogress);
  Class Clickevent implements Onclicklistener {@Override public void OnClick (View arg0) {if (arg0 = = Btnpause) {
  Player.pause (); else if (arg0 = = Btnplayurl) {//random search in Baidu MP3, you can try another link String url= "http://219.138.125.22/myweb/mp3/CMP3/JH19.
  MP3 ";
  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) {//Seekto () parameter is relative to the film time of the number, rather than the Seekbar.getmax () relative to the number player.mediaPlayer.seekTo (progress); }
 }
}

Interested readers can personally debug the example code of this article, I believe that you will understand the Android program design has played a certain role in promoting.

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.