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

Android MediaPlayer 教學:做一個能播放、暫停、快轉與回轉的音樂播放器

編輯:Android 開發實例

要在 App 裡播放一段音樂或影片,Android 提供了 MediaPlayer 這個進入點。它封裝了底層的編解碼與音訊/視訊追蹤流程,讓開發者以幾行程式碼就能完成播放、暫停、跳轉、調整音量等操作。本文從 API 講到一個功能完整的示範播放器。

建立 MediaPlayer 實例

最簡便的方式是呼叫靜態方法 create(),它會取得實例並一次完成資料源設定與準備:

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

第二個參數是媒體資源。你需要在專案的 res 底下新增一個名為 raw 的資料夾,把音樂檔放進去。放在 raw 的好處是不必自行處理檔案路徑,Android 會自動幫你配好 R.raw. 資源 ID;相對於放在 assets,取用上也更直接。

播放與暫停

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

start() 會從頭開始播;若在 pause() 之後再次呼叫 start(),則會從上次停下的位置續播,這正是多數播放器的期待行為。

若你希望無論如何都回到起點,得先重設播放器:

mediaPlayer.reset();

注意 reset() 會把播放器退回未初始化的狀態,之後必須重新設定資料源並 prepare(),不能直接 start()。

MediaPlayer 常用方法

  • isPlaying():回傳布林值,表示目前是否正在播放。
  • seekTo(int position):跳到指定的毫秒位置,是快轉與回轉的基礎。
  • getCurrentPosition():取得目前播放位置(毫秒)。
  • getDuration():取得整段媒體的總長度(毫秒)。
  • reset():重設播放器狀態。
  • release():釋放播放器持有的資源,Activity 銷毀時務必呼叫,否則會漏掉硬體解碼器。
  • setVolume(float left, float right):設定左右聲道音量,範圍 0.0 到 1.0。
  • setDataSource(FileDescriptor fd):以檔案描述項指定媒體來源。
  • selectTrack(int index):在多軌媒體中選取指定索引的軌道。
  • getTrackInfo():回傳軌道資訊陣列。

範例:具備進度條與快轉的四鍵播放器

這個範例做出一個能播放、暫停、快轉 5 秒、回退 5 秒的播放器,並用 SeekBar 即時顯示播放進度,用 Handler 每 100 毫秒更新一次時間標籤。建議在真機上實測,模擬器對音訊的支援向來不夠可靠。

實作步驟

  1. 用 Eclipse 或 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. 執行、安裝到裝置,驗證各項操作。

src/com.yiibai.mediaplayer/MainActivity.java:

package com.example.mediaplayer;

import java.util.concurrent.TimeUnit;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

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();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacks(UpdateSongTime);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}

版面配置 res/layout/activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageButton android:id="@+id/imageButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="14dp"
        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_marginLeft="22dp"
        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_marginLeft="14dp"
        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_marginLeft="24dp"
        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"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView android:id="@+id/textView2"
        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"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/imageButton3"
        android:text="@string/hello_world"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView3"
        android:src="@drawable/ic_launcher" />

    <TextView android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_toRightOf="@+id/imageButton1"
        android:text="TextView" />
</RelativeLayout>

字串資源 res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MediaPlayer</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Now Playing:</string>
    <string name="inital_Time">0 min, 0 sec</string>
</resources>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.yiibai.mediaplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />

    <application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.yiibai.mediaplayer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

執行與操作順序

假設已將 Android 手機以 USB 連上電腦。在 Eclipse 中開啟專案的任一 Activity 檔,按下工具列上的執行鈕:

Eclipse 工具列上的執行按鈕

接著會跳出裝置選擇視窗:

選擇要執行 App 的裝置

選好自己的手機,畫面上會出現播放器的初始狀態:

播放器初始畫面,暫停鈕為 disabled

預設情況下暫停鈕是灰的。按下播放鈕後,兩顆按鈕的啟用狀態會互換:

按下播放後暫停鈕變為可用

此時音樂正在播放。按下暫停鈕會看到對應的提示訊息:

按下暫停後出現暫停提示

再按一次播放,音樂會從剛剛停下的位置續播,而不是回到開頭。接著試試快轉與回退鈕,每次跳 5 秒;當已經逼近歌曲結尾而無法再往前跳時,程式會跳出提示:

無法再快轉時出現的提示訊息

切換到其他 App 時,音樂仍會在背景持續播放。要真正讓它停下來,得把這個 App 從背景工作列表中移除。

從玩具到產品還缺什麼

這個範例把播放器寫在 Activity 裡,因此螢幕旋轉或 App 被系統回收時播放狀態會憑空消失。正式產品通常會把播放控制交給 MediaSessionService(Android 8.0 以前的寫法是 MediaBrowserServiceCompat),才能正確支援通知列控制、藍牙與耳機按鍵、Android Auto 等情境;播放清單與快取則多半交給 ExoPlayer 這類專門的播放引擎。

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