Android提高第二十篇之MediaPlayer播放网络音频

 

本文来自http://blog.csdn.net/hellogv/ ,引用必须注明出处!

     以前曾经地介绍过MediaPlayer的基本用法,这里就深入地讲解MediaPlayer的在线播放功能。本文主要实现MediaPlayer在线播放音频的功能,由于在线视频播放比在线音频播放复杂,因此先介绍在线音频播放的实现,这样可以帮助大家逐步深入了解MediaPlayer的在线播放功能。先来看看本文程序运行的结果:

Android提高第二十篇之MediaPlayer播放网络音频_第1张图片

main.xml的源码如下:

view plain copy to clipboard print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_height="fill_parent" android:layout_width="fill_parent">  
  4.     <LinearLayout android:layout_height="wrap_content"  
  5.         android:layout_width="fill_parent" android:orientation="vertical"  
  6.         android:layout_gravity="top">  
  7.         <LinearLayout android:orientation="horizontal"  
  8.             android:layout_gravity="center_horizontal" android:layout_marginTop="4.0dip"  
  9.             android:layout_height="wrap_content" android:layout_width="wrap_content">  
  10.             <Button android:layout_width="wrap_content"  
  11.                 android:layout_height="wrap_content" android:id="@+id/btnPlayUrl"  
  12.                 android:text="播放网络音频"></Button>  
  13.             <Button android:layout_height="wrap_content" android:id="@+id/btnPause"  
  14.                 android:text="暂停" android:layout_width="80dip"></Button>  
  15.             <Button android:layout_height="wrap_content"  
  16.                 android:layout_width="80dip" android:text="停止" android:id="@+id/btnStop"></Button>  
  17.         </LinearLayout>  
  18.         <LinearLayout android:orientation="horizontal"  
  19.             android:layout_width="fill_parent" android:layout_height="wrap_content"  
  20.             android:layout_marginBottom="20dip">  
  21.             <SeekBar android:paddingRight="10dip" android:layout_gravity="center_vertical"  
  22.                 android:paddingLeft="10dip" android:layout_weight="1.0"  
  23.                 android:layout_height="wrap_content" android:layout_width="wrap_content"  
  24.                 android:id="@+id/skbProgress" android:max="100"></SeekBar>  
  25.         </LinearLayout>  
  26.     </LinearLayout>  
  27. </FrameLayout>  
<?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="播放网络音频"></Button><Button android:layout_height="wrap_content" android:id="@+id/btnPause"android:text="暂停" android:layout_width="80dip"></Button><Button android:layout_height="wrap_content"android:layout_width="80dip" android:text="停止" 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="100"></SeekBar></LinearLayout></LinearLayout></FrameLayout>

Player.java是本文的核心,Player.java实现了“进度条更新”、“数据缓冲”等功能,虽然不是很复杂的功能,但却是非常有用的功能。Player.java源码如下:

view plain copy to clipboard print ?
  1. package com.musicplayer;  
  2.   
  3.   
  4. import java.io.IOException;  
  5. import java.util.Timer;  
  6. import java.util.TimerTask;  
  7. import android.media.AudioManager;  
  8. import android.media.MediaPlayer;  
  9. import android.media.MediaPlayer.OnBufferingUpdateListener;  
  10. import android.media.MediaPlayer.OnCompletionListener;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.util.Log;  
  14. import android.widget.SeekBar;  
  15.   
  16. public class Player implements OnBufferingUpdateListener,  
  17.         OnCompletionListener, MediaPlayer.OnPreparedListener{  
  18.     public MediaPlayer mediaPlayer;  
  19.     private SeekBar skbProgress;  
  20.     private Timer mTimer=new Timer();  
  21.     public Player(SeekBar skbProgress)  
  22.     {  
  23.         this.skbProgress=skbProgress;  
  24.           
  25.         try {  
  26.             mediaPlayer = new MediaPlayer();  
  27.             mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);  
  28.             mediaPlayer.setOnBufferingUpdateListener(this);  
  29.             mediaPlayer.setOnPreparedListener(this);  
  30.         } catch (Exception e) {  
  31.             Log.e("mediaPlayer""error", e);  
  32.         }  
  33.           
  34.         mTimer.schedule(mTimerTask, 01000);  
  35.     }  
  36.       
  37.     /******************************************************* 
  38.      * 通过定时器和Handler来更新进度条 
  39.      ******************************************************/  
  40.     TimerTask mTimerTask = new TimerTask() {  
  41.         @Override  
  42.         public void run() {  
  43.             if(mediaPlayer==null)  
  44.                 return;  
  45.             if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {  
  46.                 handleProgress.sendEmptyMessage(0);  
  47.             }  
  48.         }  
  49.     };  
  50.       
  51.     Handler handleProgress = new Handler() {  
  52.         public void handleMessage(Message msg) {  
  53.   
  54.             int position = mediaPlayer.getCurrentPosition();  
  55.             int duration = mediaPlayer.getDuration();  
  56.               
  57.             if (duration > 0) {  
  58.                 long pos = skbProgress.getMax() * position / duration;  
  59.                 skbProgress.setProgress((int) pos);  
  60.             }  
  61.         };  
  62.     };  
  63.     //*****************************************************   
  64.       
  65.     public void play()  
  66.     {  
  67.         mediaPlayer.start();  
  68.     }  
  69.       
  70.     public void playUrl(String videoUrl)  
  71.     {  
  72.         try {  
  73.             mediaPlayer.reset();  
  74.             mediaPlayer.setDataSource(videoUrl);  
  75.             mediaPlayer.prepare();//prepare之后自动播放   
  76.             //mediaPlayer.start();   
  77.         } catch (IllegalArgumentException e) {  
  78.             // TODO Auto-generated catch block   
  79.             e.printStackTrace();  
  80.         } catch (IllegalStateException e) {  
  81.             // TODO Auto-generated catch block   
  82.             e.printStackTrace();  
  83.         } catch (IOException e) {  
  84.             // TODO Auto-generated catch block   
  85.             e.printStackTrace();  
  86.         }  
  87.     }  
  88.   
  89.       
  90.     public void pause()  
  91.     {  
  92.         mediaPlayer.pause();  
  93.     }  
  94.       
  95.     public void stop()  
  96.     {  
  97.         if (mediaPlayer != null) {   
  98.             mediaPlayer.stop();  
  99.             mediaPlayer.release();   
  100.             mediaPlayer = null;   
  101.         }   
  102.     }  
  103.   
  104.     @Override  
  105.     /**  
  106.      * 通过onPrepared播放  
  107.      */  
  108.     public void onPrepared(MediaPlayer arg0) {  
  109.         arg0.start();  
  110.         Log.e("mediaPlayer""onPrepared");  
  111.     }  
  112.   
  113.     @Override  
  114.     public void onCompletion(MediaPlayer arg0) {  
  115.         Log.e("mediaPlayer""onCompletion");  
  116.     }  
  117.   
  118.     @Override  
  119.     public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {  
  120.         skbProgress.setSecondaryProgress(bufferingProgress);  
  121.         int currentProgress=skbProgress.getMax()*mediaPlayer.getCurrentPosition()/mediaPlayer.getDuration();  
  122.         Log.e(currentProgress+"% play", bufferingProgress + "% buffer");  
  123.     }  
  124.   
  125. }  
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);}/******************************************************* * 通过定时器和Handler来更新进度条 ******************************************************/TimerTask mTimerTask = new TimerTask() {@Overridepublic void run() {if(mediaPlayer==null)return;if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {handleProgress.sendEmptyMessage(0);}}};Handler handleProgress = new Handler() {public void handleMessage(Message msg) {int position = mediaPlayer.getCurrentPosition();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();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void pause(){mediaPlayer.pause();}public void stop(){if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } }@Override/** * 通过onPrepared播放 */public void onPrepared(MediaPlayer arg0) {arg0.start();Log.e("mediaPlayer", "onPrepared");}@Overridepublic void onCompletion(MediaPlayer arg0) {Log.e("mediaPlayer", "onCompletion");}@Overridepublic void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {skbProgress.setSecondaryProgress(bufferingProgress);int currentProgress=skbProgress.getMax()*mediaPlayer.getCurrentPosition()/mediaPlayer.getDuration();Log.e(currentProgress+"% play", bufferingProgress + "% buffer");}}

test_musicplayer.java是主程序,负责调用Player类,其中关键部分是SeekBarChangeEvent这个SeekBar拖动的事件:SeekBar的Progress是0~SeekBar.getMax()之内的数,而MediaPlayer.seekTo()的参数是0~MediaPlayer.getDuration()之内数,所以MediaPlayer.seekTo()的参数是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()。

test_musicplayer.java源码如下:

view plain copy to clipboard print ?
  1. package com.musicplayer;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.SeekBar;  
  9.   
  10. public class test_musicplayer extends Activity {  
  11.     private Button btnPause, btnPlayUrl, btnStop;  
  12.     private SeekBar skbProgress;  
  13.     private Player player;  
  14.   
  15.     /** Called when the activity is first created. */  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.       
  21.         this.setTitle("在线音乐播放---hellogv编写");  
  22.   
  23.         btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);  
  24.         btnPlayUrl.setOnClickListener(new ClickEvent());  
  25.   
  26.         btnPause = (Button) this.findViewById(R.id.btnPause);  
  27.         btnPause.setOnClickListener(new ClickEvent());  
  28.   
  29.         btnStop = (Button) this.findViewById(R.id.btnStop);  
  30.         btnStop.setOnClickListener(new ClickEvent());  
  31.   
  32.         skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);  
  33.         skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());  
  34.         player = new Player(skbProgress);  
  35.   
  36.     }  
  37.   
  38.     class ClickEvent implements OnClickListener {  
  39.   
  40.         @Override  
  41.         public void onClick(View arg0) {  
  42.             if (arg0 == btnPause) {  
  43.                 player.pause();  
  44.             } else if (arg0 == btnPlayUrl) {  
  45.                 //在百度MP3里随便搜索到的,大家可以试试别的链接   
  46.                 String url="http://219.138.125.22/myweb/mp3/CMP3/JH19.MP3";  
  47.                 player.playUrl(url);  
  48.             } else if (arg0 == btnStop) {  
  49.                 player.stop();  
  50.             }  
  51.         }  
  52.     }  
  53.   
  54.     class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {  
  55.         int progress;  
  56.   
  57.         @Override  
  58.         public void onProgressChanged(SeekBar seekBar, int progress,  
  59.                 boolean fromUser) {  
  60.             // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()   
  61.             this.progress = progress * player.mediaPlayer.getDuration()  
  62.                     / seekBar.getMax();  
  63.         }  
  64.   
  65.         @Override  
  66.         public void onStartTrackingTouch(SeekBar seekBar) {  
  67.   
  68.         }  
  69.   
  70.         @Override  
  71.         public void onStopTrackingTouch(SeekBar seekBar) {  
  72.             // seekTo()的参数是相对与影片时间的数字,而不是与seekBar.getMax()相对的数字   
  73.             player.mediaPlayer.seekTo(progress);  
  74.         }  
  75.     }  
  76.   
  77. }  

你可能感兴趣的:(android,网络,layout,null,button,encoding)