在xml上建立一個seekbar:
<SeekBar
android:id="@+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
/>
Activity主要有幾個關鍵:
boolean isStart ; 紀錄TimerTask是否要運行
boolean isfirst = true; 紀錄若是第一次開啟就new Timer();
總之當歌曲播完時就先暫停TimerTask運行,等到開始播放再運行TimerTask,不然bar會亂掉
public class PlayListActivity extends Activity {
private MediaPlayer mediaplayer;
private SeekBar seekbar;
private boolean isStart ; //讓mTimerTask是否開始運行
private boolean isfirst = true;
private Timer mTimer ;
.
.
略...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
seekbar = (SeekBar) findViewById(R.id.seekbar);
.
.
略...
seekbar.setOnSeekBarChangeListener(new MySeekbar()); //bar綁定偵聽
.
.
.
//在播放部分
private void playSong(String path) {
try {
mediaplayer.reset();
mediaplayer.setDataSource(path); // 播放歌曲路徑
mediaplayer.prepare();
seekbar.setMax(mediaplayer.getDuration());//bar長度設為歌曲長度
if (isfirst) { //第一次啟用產生new Timer();
mTimer = new Timer();
mTimer.schedule(mTimerTask, 0, 300);
isfirst=false;
}
isStart = true;
mediaplayer.start(); // 開始播放
mediaplayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {//撥放完後暫停TimerTask
isStart = false;
nextSong(); // 播放完後播下一首
}
});
} catch (IOException e) {
}
}
private TimerTask mTimerTask = new TimerTask() {
@Override
public void run() {
if(isStart) { //如果isStart = true,開始運行
seekbar.setProgress(mediaplayer.getCurrentPosition());
} //TimerTask會一直更新,使bar會隨著歌曲播放而改變bar位置
}
};
//進度條處理
class MySeekbar implements OnSeekBarChangeListener {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
//拖移進度條時,TimerTask暫停運行,不然在你沒放開手指前bar會一直亂跳
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
isStart = false;
}
//放開進度條時,TimerTask運行,歌曲會因為你拖移進度條放開後改變播放位置
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
isStart = true;
mediaplayer.seekTo(seekbar.getProgress());
}
}