mMediaPlayer 播放网络mp3
1.异步准备
使用
mMediaPlayer.prepareAsync();
2.监听prepareAsync结果
使用MediaPlayer.OnPreparedListener
3.获取长度
在public void onPrepared(MediaPlayer mp) 方法中可以获得长度
int duration = mMediaPlayer.getDuration();
4.获取缓存进度
使用:MediaPlayer.OnBufferingUpdateListener
大概代码像下面这样:
mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { btPlayStop.setEnabled(true); int duration = mMediaPlayer.getDuration(); sbMusicProcess.setMax(duration); mHandler.sendEmptyMessage(1); mMediaPlayer.start(); btPlayStop.setChecked(PLAYING); } }); try { mMediaPlayer.setDataSource(mp3url); } catch (IOException e) { e.printStackTrace(); } mMediaPlayer.prepareAsync(); mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { runOnUiThread(new Runnable() { @Override public void run() { sbMusicProcess.setSecondaryProgress((sbMusicProcess.getMax() * process / 100)); } }); } }); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.reset(); btPlayStop.setChecked(READY); } });
prepare 与prepareAsync()的区别
后台推荐网络和异步使用。
prepareAsync()工作原理分析
参考:
http://blog.csdn.net/hejjunlin/article/details/52420803
至此MediaPlayer已可以满足基本的音乐播放需求。