想在自己的 App 裡放一段音樂,其實不需要複雜的架構。整個專案只有一個主 Activity,介面配置也相當樸素:一個輸入框填寫檔名,加上開始、暫停、重播、停止四顆按鈕。真正的重點在於 MediaPlayer 的狀態管理,以及 Activity 生命週期與播放進度的配合。
目錄結構維持 Android 專案的典型樣貌,唯一需要留意的是音樂檔要放在 SD 卡(外部儲存空間)根目錄,程式會用 Environment.getExternalStorageDirectory() 拼出絕對路徑,例如 /mnt/sdcard/saybye.mp3。
package sn.len.music;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MusicPlayerActivity extends Activity implements OnClickListener {
private EditText editText;
private MediaPlayer mediaPlayer;
private String fileName = null;
private int postition;
private static final String TAG = "MusicPlayerActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
editText = (EditText) findViewById(R.id.option);
fileName = editText.getText().toString();
Button start = (Button) findViewById(R.id.start);
Button pause = (Button) findViewById(R.id.pause);
Button replay = (Button) findViewById(R.id.replay);
Button stop = (Button) findViewById(R.id.stop);
start.setOnClickListener(this);
pause.setOnClickListener(this);
replay.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Button continue_but = (Button) v;
try {
switch (v.getId()) {
case R.id.start: // 開始
play();
break;
case R.id.pause: // 暫停 / 繼續
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
continue_but.setText(R.string.conti);
} else {
mediaPlayer.start();
continue_but.setText(R.string.pause);
}
break;
case R.id.replay: // 重播
if (mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(0);
} else {
play();
}
break;
case R.id.stop: // 停止
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
break;
default:
break;
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
private void play() throws IOException {
// 檔案在 SD 卡,先組出 File 物件
File file = new File(Environment.getExternalStorageDirectory(), fileName);
mediaPlayer.reset();
mediaPlayer.setDataSource(file.getAbsolutePath());
Log.i("ABS", file.getAbsolutePath());
mediaPlayer.prepare(); // 初始化、緩衝
mediaPlayer.start(); // 開始播放
}
@Override
protected void onDestroy() {
mediaPlayer.release(); // 釋放資源
super.onDestroy();
}
}
單純會播放並不算完整,來電或切換頁面時音樂必須自動讓位,回來時還要能從原本的位置接著放。做法是在 onPause() 記下目前播放位置並暫停,在 onResume() 重新載入後 seekTo() 跳回斷點:
@Override
protected void onPause() {
if (mediaPlayer.isPlaying()) {
postition = mediaPlayer.getCurrentPosition(); // 記錄斷點
mediaPlayer.pause();
}
super.onPause();
}
@Override
protected void onResume() {
if (postition > 0 && fileName != null) {
try {
play();
mediaPlayer.seekTo(postition); // 回到指定位置
postition = 0;
} catch (IOException e) {
e.printStackTrace();
}
}
super.onResume();
}
若再把斷點與檔名寫進 onSaveInstanceState(),並在 onRestoreInstanceState() 讀回來,即使系統因記憶體不足把程式回收,下次開啟仍能接續上次的進度:
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("postition", postition);
outState.putString("fileName", fileName);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
postition = savedInstanceState.getInt("postition");
fileName = savedInstanceState.getString("fileName");
super.onRestoreInstanceState(savedInstanceState);
}
别忘了在清單檔註冊讀取外部儲存空間的權限,並在下載或新增音樂後執行一次媒體掃描,否則 setDataSource() 會因為找不到檔案而丟出 IOException。另外 stop() 之後的 MediaPlayer 進入 Stopped 狀態,必須再呼叫 prepare() 才能重新播放,這也是範例中重播時走 play() 而非直接 start() 的原因。