Android本地音樂播放

我叫阿狸貓發表於2014-12-08

主要就是用到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);
		}
	}
}
效果如下:





相關文章