代码部分
package com.example.song.lx_android_day04_musicplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
private MediaPlayer player;//创建音乐播放器
private Button pause;
private Button start;
private Button stop;
private SeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();//初始化控件
setListener();//设置控件的监听事件
}
private void setListener() {
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (player != null) {
player.pause();//暂停
}
}
});
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (player != null) {
player.start();//开始播放
//调用run开始更新进度条
handler.post(run);
}
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (player != null) {
player.pause();
//暂停使音乐回到最开始
player.seekTo(0);
}
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(run);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.seekTo(seekBar.getProgress());
handler.postDelayed(run, 1000);
}
});
}
Handler handler = new Handler();
Runnable run = new Runnable() {
@Override
public void run() {
//player.getCurrentPosition()获取音乐的当前进度
seekBar.setProgress(player.getCurrentPosition());
handler.postDelayed(run, 100);
}
};
private void initView() {
pause = ((Button) findViewById(R.id.pause));
start = ((Button) findViewById(R.id.start));
stop = ((Button) findViewById(R.id.stop));
seekBar = ((SeekBar) findViewById(R.id.seekBar));
/**
* 初始化音乐播放器
* 参数1 上下文对象
* 参数2 资源 也可以是一个网址比如 http//xxxxxx.mp3
* 第二个参数填上地址就可以实现在线播放了
*/
player = MediaPlayer.create(this, R.raw.thoseflower);
int max = player.getDuration();//获取音乐的播放时间 单位是毫秒
seekBar.setMax(max);//设置SeekBar的播放时间
}
}
布局