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

Android MediaPlayer 實戰:播放、暫停、快轉,一個都不能少

編輯:Android 開發實例

要在 App 裡放音樂或影片,Android 提供了 MediaPlayer 這個類別作為進入點。它被封裝在系統的媒體播放服務之上,讓你不必自己處理解碼細節,就能播放本機資源、SD 卡檔案,甚至是網路上的串流來源。

建立播放器實體

最簡便的方式是呼叫靜態方法 create(),它會幫你完成建立與準備(prepare)兩個步驟,直接回傳一個可用的 MediaPlayer 物件:

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()回傳 true/false,表示目前是否正在播放。
seekTo(int ms)跳到指定的毫秒位置,實作快轉與快退就靠它。
getCurrentPosition()取得目前的播放位置,單位是毫秒。
getDuration()取得整首曲子的總長度,單位是毫秒。
reset()把播放器重設回初始狀態。
release()釋放播放器持有的所有資源,離開畫面前務必呼叫。
setVolume(float left, float right)分別設定左右聲道的音量,範圍 0.0 到 1.0。
setLooping(boolean)是否要循環播放。
prepare() / prepareAsync()為播放做準備;若資料來源是網路,請用非同步版本以免卡住 UI 執行緒。

實作範例:一個有快轉與快退的播放器

這個範例會做出一個能播放、暫停、往前跳 5 秒、往後跳 5 秒,並帶有進度條與時間顯示的迷你播放器。由於要聽聲音,建議直接跑在實機上。

步驟做法
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在 MediaPlayer 專案下新增 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(四顆 ImageButton 分別接上 forward、rewind、pause、play,SeekBar 夾在左右時間文字之間):

<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/textView2"
        android:layout_toRightOf="@+id/textView1" />

    <TextView android:id="@+id/textView1"
        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>

把實機連上電腦,在 Eclipse 或 Android Studio 中按下執行鈕:

工具列上的執行按鈕

選擇你的裝置作為執行目標:

選擇執行裝置

App 啟動後的預設狀態,暫停鈕是灰色的、播放鈕可用:

播放器初始狀態

按下播放鈕,播放鈕變灰、暫停鈕亮起,時間與進度條同步開始走:

正在播放的狀態

按下暫停鈕,畫面會跳出暫停的提示訊息:

暫停播放的提示

此時再按播放,音樂會從剛剛停住的地方續播,而不是回到開頭。按快轉或快退則可前後跳 5 秒;如果已經快轉到曲尾再按,就會看到「無法再往前跳」的提示:

無法再快轉時的提示訊息

當你切到其他 App 時,音樂仍會在背景持續播放。若要讓它停下來,必須回到這個 App 並結束它。

兩個必須補上的觀念:範例中透過 Handler.postDelayed() 每 100 毫秒更新一次進度條,這在離開 Activity 時必須一併移除回呼(myHandler.removeCallbacks(UpdateSongTime)),並在 onDestroy() 中呼叫 mediaPlayer.release(),否則會造成記憶體與音訊資源的洩漏。另外,若你希望音樂在切換 App 後仍能被系統妥善管理,正式專案應該改用 MediaSession 搭配前景服務(Foreground Service),而不是像範例這樣讓 MediaPlayer 孤零零地留在背景。

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