/**
* MediaPlayer的两种创建方式 1.静态的 raw
*
* @author Administrator
*
*/
public class MainActivity extends Activity implements OnClickListener {
// 文件路径
private String path1 = “mnt/sdcard/ha.mp3”;
private MediaPlayer mediaPlayer;
private boolean isPuase = true;
private Button pause;
private SeekBar seekBar;
private Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化界面
initViews();
}
private void initViews() {
Button play = (Button) findViewById(R.id.play);
Button stop = (Button) findViewById(R.id.stop);
pause = (Button) findViewById(R.id.pause);
seekBar = (SeekBar) findViewById(R.id.seek);
//设置拖动监听
seekBar.setOnSeekBarChangeListener(new MySeekBar());
play.setOnClickListener(this);
stop.setOnClickListener(this);
pause.setOnClickListener(this);
}
//拖动监听
class MySeekBar implements OnSeekBarChangeListener{
//onProgressChanged 当进度改变时调用
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
// 开始拖动的时候调用
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
//当停止拖动的时候调用
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//获取seekBar 的位置
int progress = seekBar.getProgress();
//设置播放的进度
mediaPlayer.seekTo(progress);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
// 播放
case R.id.play:
Toast.makeText(MainActivity.this, "播放", 0).show();
mediaPlayer = new MediaPlayer();
// 1.重置
mediaPlayer.reset();
// 2.设置资源
try {
mediaPlayer.setDataSource(path1);
//设置seekbar的总长度
// 3.准备
mediaPlayer.prepare();
// 4,开始播放
mediaPlayer.start();
int duration = mediaPlayer.getDuration();//获取总时长
seekBar.setMax(duration);
timer = new Timer();
timer.schedule(new MyTask(), 0, 1000);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 停止
case R.id.stop:
// 停止播放
if (mediaPlayer != null) {
mediaPlayer.stop();
}
break;
// 暂停和继续播放
case R.id.pause:
if (isPuase) {
mediaPlayer.pause();
pause.setText("继续播放");
} else {
mediaPlayer.start();
pause.setText("暂停");
}
isPuase = !isPuase;
break;
default:
break;
}
}
//计时器任务栈
class MyTask extends TimerTask{
@Override
public void run() {
Log.e("Main-->", "获取进度");
int currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
}
}
}