下面介绍具体实现过程:
定义一个具有缓冲效果的播放器:Player
我们看到的缓冲效果,是通过设置拖动条SeekBar的二级进度实现的,这就要设置MediaPlayer的缓冲更新的监听了。
具体代码实现:
package com.wwj.download.util;
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.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.util.Log;
import android.widget.SeekBar;
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener {
public MediaPlayer mediaPlayer; // 媒体播放器
private SeekBar seekBar; // 拖动条
private Timer mTimer = new Timer(); // 计时器
// 初始化播放器
public Player(SeekBar seekBar) {
super();
this.seekBar = seekBar;
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
e.printStackTrace();
}
// 每一秒触发一次
mTimer.schedule(timerTask, 0, 1000);
}
// 计时器
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && seekBar.isPressed() == false) {
handler.sendEmptyMessage(0); // 发送消息
}
}
};
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
// 计算进度(获取进度条最大刻度*当前音乐播放位置 / 当前音乐时长)
long pos = seekBar.getMax() * position / duration;
seekBar.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
/**