packagecom.wuyudong.mp3player;importjava.io.File;importjava.io.IOException;importandroid.media.AudioManager;importandroid.media.MediaPlayer;importandroid.media.MediaPlayer.OnCompletionListener;importandroid.net.Uri;importandroid.os.Bundle;importandroid.app.Activity;importandroid.view.Menu;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.Toast;public class MainActivity extends Activity implementsOnClickListener {privateEditText et_path;privateButton bt_play, bt_replay, bt_pause, bt_stop;privateMediaPlayer mediaPlayer;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path=(EditText) findViewById(R.id.et_path);
bt_play=(Button) findViewById(R.id.bt_play);
bt_replay=(Button) findViewById(R.id.bt_replay);
bt_pause=(Button) findViewById(R.id.bt_pause);
bt_stop=(Button) findViewById(R.id.bt_stop);
bt_pause.setOnClickListener(this);
bt_play.setOnClickListener(this);
bt_replay.setOnClickListener(this);
bt_stop.setOnClickListener(this);
}
@Overridepublic voidonClick(View v) {switch(v.getId()) {caseR.id.bt_play:
play();break;caseR.id.bt_replay:
replay();break;caseR.id.bt_stop:
stop();break;caseR.id.bt_pause:
pause();break;default:break;
}
}/*** 暂停音乐*/
private voidpause() {if ("继续".equals(bt_pause.getText().toString().trim())) {
mediaPlayer.start();
bt_pause.setText("暂停");return;
}if (mediaPlayer != null &&mediaPlayer.isPlaying()) {
mediaPlayer.pause();
bt_pause.setText("继续");return;
}
}/*** 重新播放*/
private voidreplay() {if (mediaPlayer != null &&mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(0);return;
}
play();
}/*** 停止播放音乐*/
private voidstop() {if (mediaPlayer != null &&mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();//记得释放资源
mediaPlayer = null;
bt_play.setEnabled(true);
}
}/*** 播放音乐*/
private voidplay() {
String path=et_path.getText().toString().trim();
File file= newFile(path);if (file.exists() && file.length() > 0) {try{
mediaPlayer= newMediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();//might take long! (for buffering, etc)
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(newOnCompletionListener() {
@Overridepublic voidonCompletion(MediaPlayer mp) {
bt_play.setEnabled(true);
}
} );
bt_play.setEnabled(false);
}catch(Exception e) {
Toast.makeText(this, "播放失败", 0).show();
e.printStackTrace();
}
}else{
Toast.makeText(this, "文件不存在", 0).show();
}
}
}