主要就是用到MediaPlayer类里的API
public class MainActivity extends Activity {
private TextView et_path;
private Button bt_play;
private Button bt_pause;
private Button bt_stop;
private Button bt_replay;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
et_path = (TextView) findViewById(R.id.et_path);
bt_play = (Button) findViewById(R.id.bt_play);
bt_pause = (Button) findViewById(R.id.bt_pause);
bt_stop = (Button) findViewById(R.id.bt_stop);
bt_replay = (Button) findViewById(R.id.bt_replay);
}
public void play(View view) {
String path = et_path.getText().toString();
File file = new File(path);
if(!file.exists()){
Toast.makeText(getApplicationContext(), "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
bt_play.setEnabled(false); //设置按钮不可按
mediaPlayer.setOnCompletionListener(new OnCompletionListener() { //播放完成时的回调方法
@Override
public void onCompletion(MediaPlayer mp) {
bt_play.setEnabled(true); //设置按钮可按
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "播放失败", Toast.LENGTH_SHORT).show();
}
}
public void pause(View view) {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){ //在播放状态按暂停后
mediaPlayer.pause(); //播放暂停
bt_pause.setText("继续"); //暂停按钮显示继续
}else if(mediaPlayer!=null&&!mediaPlayer.isPlaying()){ //在暂停状态按继续后
mediaPlayer.start(); //播放继续
bt_pause.setText("暂停"); //暂停按钮显示暂停
}
}
public void stop(View view) {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop(); //暂停播放
mediaPlayer.release(); //释放资源
mediaPlayer = null;
}
}
public void replay(View view) {
if(mediaPlayer!=null){
mediaPlayer.reset();
//或者
//mediaPlayer.seekTo(0);
}
}
}
效果如下: