Android:音乐播放器(2)—加进度条
程序员文章站
2024-01-11 20:37:28
...
加进度条
MainActivity代码如下:
public class Main3Activity extends AppCompatActivity {
private Button start,end,pause;
MediaPlayer mediaPlayer;
private SeekBar seekBar;
Timer timer = new Timer();;
TimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
start = (Button) findViewById(R.id.start);
end = (Button) findViewById(R.id.end);
pause = (Button) findViewById(R.id.pause);
seekBar = (SeekBar) findViewById(R.id.seekBar);
Intent intent = getIntent();
String url = intent.getStringExtra("url");
// mediaPlayer = MediaPlayer.create(Main3Activity.this, Uri.parse(url));
mediaPlayer = MediaPlayer.create(Main3Activity.this,R.raw.a);
//歌曲的播放时长
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i("messgae","start");
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i("messgae","stop");
//设置歌曲的进度为进度条的位置
mediaPlayer.seekTo(seekBar.getProgress());
}
});
}
public void click(View view){
int id = view.getId();
switch(id){
case R.id.start:
start();
break;
case R.id.end:
stop();
break;
case R.id.pause:
pause();
break;
}
}
public void start(){
mediaPlayer.start();
timerTask = new TimerTask() {
@Override
public void run() {
//歌曲当前播放位置
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
};
//1.等多久再执行什么
//2.每隔多久执行一次什么
timer.schedule(timerTask,0,100);
start.setEnabled(false);
}
public void pause(){
String pause1 = pause.getText().toString().trim();
if("暂停".equals(pause1)){
mediaPlayer.pause();
pause.setText("继续");
}else{
mediaPlayer.start();
pause.setText("暂停");
}
}
public void stop(){
if(mediaPlayer!=null){
timer.cancel();
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
start.setEnabled(true);
}
}
}