Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android MediaPlayer 完整指南:從 create() 到快轉快退與資源釋放

編輯:Android 開發實例

要在 App 裡播放音樂,Android 給的第一個答案就是 MediaPlayer。它位於系統媒體播放服務之上,把容器格式解析、音訊解碼、輸出路由這些麻煩事都封裝起來,開發者只要下達「播放這個來源」、「暫停」、「跳到第幾毫秒」這類指令即可。

建立與播放

最簡潔的寫法是靜態方法 create(),它會完成建立與準備兩個階段,直接回傳可用的物件:

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

第二個參數是資源 id。使用前請在專案裡建立名為 raw 的資料夾,把音樂檔(例如 song.mp3)放進去,Android 便會自動產生 R.raw.song 參照。

有了物件,就能控制播放:

mediaPlayer.start();
mediaPlayer.pause();

要特別注意行為差異:start() 首次呼叫時從頭開始,但在 pause() 之後再呼叫 start(),會從暫停處續播。想強制回到開頭,得先 reset():

mediaPlayer.reset();

常用方法整理

方法說明
isPlaying()回傳是否正在播放。
seekTo(int ms)跳至指定毫秒位置。
getCurrentPosition()目前播放位置(毫秒)。
getDuration()音檔總長度(毫秒)。
reset()重設播放器。
release()釋放播放器持有的資源。
setVolume(float left, float right)設定左右聲道音量。
setLooping(boolean)是否循環播放。
prepareAsync()非同步準備,適合網路來源。

範例:具備快轉快退的迷你播放器

這個範例會做出播放、暫停、前後跳 5 秒的功能,並搭配 SeekBar 與時間標示。由於要實際出聲,建議跑在真機上。

步驟做法
1用 Android Studio 建立專案 MediaPlayer(套件 com.yiibai.mediaplayer),Target SDK 與 Compile With 選最新版本。
2修改 src/MainActivity.java,加入 MediaPlayer 邏輯。
3修改 res/layout/activity_main.xml,放入四顆 ImageButton 與 SeekBar。
4修改 res/values/strings.xml,補上文字資源。
5新增 raw 資料夾並放入 song.mp3。
6執行 App 並在裝置上驗證。

MainActivity.java:

public class MainActivity extends Activity {
    public TextView songName, startTimeField, endTimeField;
    private MediaPlayer mediaPlayer;
    private double startTime = 0;
    private double finalTime = 0;
    private Handler myHandler = new Handler();
    private int forwardTime = 5000;
    private int backwardTime = 5000;
    private SeekBar seekbar;
    private ImageButton playButton, pauseButton;
    public static int oneTimeOnly = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        songName       = (TextView) findViewById(R.id.textView4);
        startTimeField = (TextView) findViewById(R.id.textView1);
        endTimeField   = (TextView) findViewById(R.id.textView2);
        seekbar     = (SeekBar) findViewById(R.id.seekBar1);
        playButton  = (ImageButton) findViewById(R.id.imageButton1);
        pauseButton = (ImageButton) findViewById(R.id.imageButton2);

        songName.setText("song.mp3");
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
        seekbar.setClickable(false);
        pauseButton.setEnabled(false);
    }

    public void play(View view) {
        Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
        mediaPlayer.start();
        finalTime = mediaPlayer.getDuration();
        startTime = mediaPlayer.getCurrentPosition();

        if (oneTimeOnly == 0) {
            seekbar.setMax((int) finalTime);
            oneTimeOnly = 1;
        }
        endTimeField.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
            TimeUnit.MILLISECONDS.toSeconds((long) finalTime)
            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))));
        startTimeField.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime)
            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))));
        seekbar.setProgress((int) startTime);

        myHandler.postDelayed(UpdateSongTime, 100);
        pauseButton.setEnabled(true);
        playButton.setEnabled(false);
    }

    private Runnable UpdateSongTime = new Runnable() {
        public void run() {
            startTime = mediaPlayer.getCurrentPosition();
            startTimeField.setText(String.format("%d min, %d sec",
                TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                TimeUnit.MILLISECONDS.toSeconds((long) startTime)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))));
            seekbar.setProgress((int) startTime);
            myHandler.postDelayed(this, 100);
        }
    };

    public void pause(View view) {
        Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show();
        mediaPlayer.pause();
        pauseButton.setEnabled(false);
        playButton.setEnabled(true);
    }

    public void forward(View view) {
        int temp = (int) startTime;
        if ((temp + forwardTime) <= finalTime) {
            startTime = startTime + forwardTime;
            mediaPlayer.seekTo((int) startTime);
        } else {
            Toast.makeText(getApplicationContext(),
                "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();
        }
    }

    public void rewind(View view) {
        int temp = (int) startTime;
        if ((temp - backwardTime) > 0) {
            startTime = startTime - backwardTime;
            mediaPlayer.seekTo((int) startTime);
        } else {
            Toast.makeText(getApplicationContext(),
                "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show();
        }
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton android:id="@+id/imageButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:onClick="forward"
        android:src="@android:drawable/ic_media_ff" />

    <ImageButton android:id="@+id/imageButton4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/imageButton2"
        android:layout_toRightOf="@+id/imageButton2"
        android:onClick="rewind"
        android:src="@android:drawable/ic_media_rew" />

    <ImageButton android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageButton1"
        android:layout_toRightOf="@+id/imageButton1"
        android:onClick="pause"
        android:src="@android:drawable/ic_media_pause" />

    <ImageButton android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageButton3"
        android:layout_toRightOf="@+id/imageButton3"
        android:onClick="play"
        android:src="@android:drawable/ic_media_play" />

    <SeekBar android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageButton3"
        android:layout_toLeftOf="@+id/textValue2"
        android:layout_toRightOf="@+id/textValue1" />

    <TextView android:id="@+id/textValue1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/imageButton3"
        android:layout_alignTop="@+id/seekBar1"
        android:text="@string/inital_Time" />

    <TextView android:id="@+id/textValue2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/imageButton4"
        android:layout_alignTop="@+id/seekBar1"
        android:text="@string/inital_Time" />

    <TextView android:id="@+id/textValue3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/imageButton3"
        android:text="@string/hello_world" />

    <TextView android:id="@+id/textValue4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textValue3"
        android:layout_alignBottom="@+id/textValue3"
        android:layout_toRightOf="@+id/imageButton1"
        android:text="TextView" />

</RelativeLayout>

strings.xml:

<resources>
    <string name="app_name">MediaPlayer</string>
    <string name="hello_world">Now Playing:</string>
    <string name="inital_Time">0 min, 0 sec</string>
</resources>

假設已將真機連上電腦。開啟專案的 Activity 檔,按下工具列的執行鈕:

工具列上的執行按鈕

IDE 會先顯示選擇視窗,讓你決定要跑在哪個目標上:

選擇執行裝置

選用手機作為執行目標,裝置上便會出現播放器畫面:

播放器預設畫面

預設狀態下暫停鈕是 disabled。按下播放鈕後兩者狀態互換,時間與進度條同步推進:

播放中的狀態

按下暫停鈕,會看到暫停的提示訊息:

暫停提示

再按播放會從暫停處續播,而非回到開頭。按快轉或快退可跳 5 秒;當已達曲尾仍再按快轉,就會出現提示:

無法再快轉時的提示

當你切換到其他 App,音樂仍會在背景持續播放;要停止它,必須回到這個 App 並結束該程式。

三個正式專案必做的補強:其一,範例以 Handler.postDelayed() 每 100 毫秒更新進度,離開時請呼叫 myHandler.removeCallbacks(UpdateSongTime),並在 onDestroy() 中執行 mediaPlayer.release(),否則音訊資源不會釋放。其二,若要支援通知列與鎖定螢幕的控制按鈕,應改用 MediaSession 搭配前景服務,讓系統能正確管理播放狀態。其三,範例播放的是本機 raw 資源;若來源是網路網址,請改用 setDataSource(url) 搭配 prepareAsync() 與 OnPreparedListener,並在 AndroidManifest.xml 加上 INTERNET 權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved