前面有一个简单的音乐播放器,能够简单的播放歌曲,这里实现稍微完善的播放器。
音乐播放器
播放服务
播放音频的代码应该运行在服务中,定义一个播放服务MusicService服务里定义play、stop、pause、continuePlay等方法
private void play() {
player.reset();
try {
player.setDataSource("sdcard/bzj.mp3");
player.prepare();
} catch (Exception e) {
e.printStackTrace();
}
player.start();
}
private void pause() {
player.pause();
}
private void stop() {
player.stop();
}
private void continuePlay() {
player.start();
}
把这几个方法抽取成一个接口MusicInterface 定义一个中间人类,继承Binder,实现MusicInterface先start启动MusicService,再bind
Intent intent = new Intent(this, MusicService.class);
startService(intent);
bindService(intent, conn, BIND_AUTO_CREATE);
根据播放进度设置进度条
获取当前的播放时间和当前音频的最长时间
int currentPosition = player.getCurrentPosition();
int duration = player.getDuration();
播放进度需要不停的获取,不停的刷新进度条,使用计时器每500毫秒获取一次播放进度发消息至Handler,把播放进度放进Message对象中,在Handler中更新SeekBar的进度
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
int currentPosition = player.getCurrentPosition();
int duration = player.getDuration();
Message msg = Message.obtain();
//把播放进度存入Message中
Bundle data = new Bundle();
data.putInt("currentPosition", currentPosition);
data.putInt("duration", duration);
msg.setData(data);
MainActivity.handler.sendMessage(msg);
}
}, 5, 500);
在Activity中定义Handler
static Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
//取出消息携带的数据
Bundle data = msg.getData();
int currentPosition = data.getInt("currentPosition");
int duration = data.getInt("duration");
//设置播放进度
sb.setMax(duration);
sb.setProgress(currentPosition);
};
};
拖动进度条改变播放进度
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
mi.seekTo(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
中间人接口
public interface MusicInterface {
void seekTo(int progress);
服务
public class MusicService extends Service {
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new MusicController();
class MusicController extends Binder implements MusicInterface{
MusicService.this.play();
MusicService.this.pause();