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

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

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

main.xml的源码如下:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_height="fill_parent"android:layout_width="fill_parent">
  4. <LinearLayoutandroid:layout_height="wrap_content"
  5. android:layout_width="fill_parent"android:orientation="vertical"
  6. android:layout_gravity="top">
  7. <LinearLayoutandroid: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. <Buttonandroid:layout_width="wrap_content"
  11. android:layout_height="wrap_content"android:id="@+id/btnPlayUrl"
  12. android:text="播放网络音频"></Button>
  13. <Buttonandroid:layout_height="wrap_content"android:id="@+id/btnPause"
  14. android:text="暂停"android:layout_width="80dip"></Button>
  15. <Buttonandroid:layout_height="wrap_content"
  16. android:layout_width="80dip"android:text="停止"android:id="@+id/btnStop"></Button>
  17. </LinearLayout>
  18. <LinearLayoutandroid:orientation="horizontal"
  19. android:layout_width="fill_parent"android:layout_height="wrap_content"
  20. android:layout_marginBottom="20dip">
  21. <SeekBarandroid: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>

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

  1. packagecom.musicplayer;
  2. importjava.io.IOException;
  3. importjava.util.Timer;
  4. importjava.util.TimerTask;
  5. importandroid.media.AudioManager;
  6. importandroid.media.MediaPlayer;
  7. importandroid.media.MediaPlayer.OnBufferingUpdateListener;
  8. importandroid.media.MediaPlayer.OnCompletionListener;
  9. importandroid.os.Handler;
  10. importandroid.os.Message;
  11. importandroid.util.Log;
  12. importandroid.widget.SeekBar;
  13. publicclassPlayerimplementsOnBufferingUpdateListener,
  14. OnCompletionListener,MediaPlayer.OnPreparedListener{
  15. publicMediaPlayermediaPlayer;
  16. privateSeekBarskbProgress;
  17. privateTimermTimer=newTimer();
  18. publicPlayer(SeekBarskbProgress)
  19. {
  20. this.skbProgress=skbProgress;
  21. try{
  22. mediaPlayer=newMediaPlayer();
  23. mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  24. mediaPlayer.setOnBufferingUpdateListener(this);
  25. mediaPlayer.setOnPreparedListener(this);
  26. }catch(Exceptione){
  27. Log.e("mediaPlayer","error",e);
  28. }
  29. mTimer.schedule(mTimerTask,0,1000);
  30. }
  31. /*******************************************************
  32. *通过定时器和Handler来更新进度条
  33. ******************************************************/
  34. TimerTaskmTimerTask=newTimerTask(){
  35. @Override
  36. publicvoidrun(){
  37. if(mediaPlayer==null)
  38. return;
  39. if(mediaPlayer.isPlaying()&&skbProgress.isPressed()==false){
  40. handleProgress.sendEmptyMessage(0);
  41. }
  42. }
  43. };
  44. HandlerhandleProgress=newHandler(){
  45. publicvoidhandleMessage(Messagemsg){
  46. intposition=mediaPlayer.getCurrentPosition();
  47. intduration=mediaPlayer.getDuration();
  48. if(duration>0){
  49. longpos=skbProgress.getMax()*position/duration;
  50. skbProgress.setProgress((int)pos);
  51. }
  52. };
  53. };
  54. //*****************************************************
  55. publicvoidplay()
  56. {
  57. mediaPlayer.start();
  58. }
  59. publicvoidplayUrl(StringvideoUrl)
  60. {
  61. try{
  62. mediaPlayer.reset();
  63. mediaPlayer.setDataSource(videoUrl);
  64. mediaPlayer.prepare();//prepare之后自动播放
  65. //mediaPlayer.start();
  66. }catch(IllegalArgumentExceptione){
  67. //TODOAuto-generatedcatchblock
  68. e.printStackTrace();
  69. }catch(IllegalStateExceptione){
  70. //TODOAuto-generatedcatchblock
  71. e.printStackTrace();
  72. }catch(IOExceptione){
  73. //TODOAuto-generatedcatchblock
  74. e.printStackTrace();
  75. }
  76. }
  77. publicvoidpause()
  78. {
  79. mediaPlayer.pause();
  80. }
  81. publicvoidstop()
  82. {
  83. if(mediaPlayer!=null){
  84. mediaPlayer.stop();
  85. mediaPlayer.release();
  86. mediaPlayer=null;
  87. }
  88. }
  89. @Override
  90. /**
  91. *通过onPrepared播放
  92. */
  93. publicvoidonPrepared(MediaPlayerarg0){
  94. arg0.start();
  95. Log.e("mediaPlayer","onPrepared");
  96. }
  97. @Override
  98. publicvoidonCompletion(MediaPlayerarg0){
  99. Log.e("mediaPlayer","onCompletion");
  100. }
  101. @Override
  102. publicvoidonBufferingUpdate(MediaPlayerarg0,intbufferingProgress){
  103. skbProgress.setSecondaryProgress(bufferingProgress);
  104. intcurrentProgress=skbProgress.getMax()*mediaPlayer.getCurrentPosition()/mediaPlayer.getDuration();
  105. Log.e(currentProgress+"%play",bufferingProgress+"%buffer");
  106. }
  107. }

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源码如下:

  1. packagecom.musicplayer;
  2. importandroid.app.Activity;
  3. importandroid.os.Bundle;
  4. importandroid.view.View;
  5. importandroid.view.View.OnClickListener;
  6. importandroid.widget.Button;
  7. importandroid.widget.SeekBar;
  8. publicclasstest_musicplayerextendsActivity{
  9. privateButtonbtnPause,btnPlayUrl,btnStop;
  10. privateSeekBarskbProgress;
  11. privatePlayerplayer;
  12. /**Calledwhentheactivityisfirstcreated.*/
  13. @Override
  14. publicvoidonCreate(BundlesavedInstanceState){
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. this.setTitle("在线音乐播放---hellogv编写");
  18. btnPlayUrl=(Button)this.findViewById(R.id.btnPlayUrl);
  19. btnPlayUrl.setOnClickListener(newClickEvent());
  20. btnPause=(Button)this.findViewById(R.id.btnPause);
  21. btnPause.setOnClickListener(newClickEvent());
  22. btnStop=(Button)this.findViewById(R.id.btnStop);
  23. btnStop.setOnClickListener(newClickEvent());
  24. skbProgress=(SeekBar)this.findViewById(R.id.skbProgress);
  25. skbProgress.setOnSeekBarChangeListener(newSeekBarChangeEvent());
  26. player=newPlayer(skbProgress);
  27. }
  28. classClickEventimplementsOnClickListener{
  29. @Override
  30. publicvoidonClick(Viewarg0){
  31. if(arg0==btnPause){
  32. player.pause();
  33. }elseif(arg0==btnPlayUrl){
  34. //在百度MP3里随便搜索到的,大家可以试试别的链接
  35. Stringurl="http://219.138.125.22/myweb/mp3/CMP3/JH19.MP3";
  36. player.playUrl(url);
  37. }elseif(arg0==btnStop){
  38. player.stop();
  39. }
  40. }
  41. }
  42. classSeekBarChangeEventimplementsSeekBar.OnSeekBarChangeListener{
  43. intprogress;
  44. @Override
  45. publicvoidonProgressChanged(SeekBarseekBar,intprogress,
  46. booleanfromUser){
  47. //原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
  48. this.progress=progress*player.mediaPlayer.getDuration()
  49. /seekBar.getMax();
  50. }
  51. @Override
  52. publicvoidonStartTrackingTouch(SeekBarseekBar){
  53. }
  54. @Override
  55. publicvoidonStopTrackingTouch(SeekBarseekBar){
  56. //seekTo()的参数是相对与影片时间的数字,而不是与seekBar.getMax()相对的数字
  57. player.mediaPlayer.seekTo(progress);
  58. }
  59. }
  60. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值