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

Android 音樂播放器實作:MediaPlayer 搭配 SeekBar 的完整流程

編輯:Android 開發實例

Android 想播放一段音訊或影片,最直接的入口就是 MediaPlayer。它站在系統的媒體播放服務之上,把解碼、音訊輸出這些底層細節都收 ourselves 起來,開發者只要告訴它「播這個來源」、「現在暫停」、「跳到第 30 秒」,它就會照辦。

建立播放器

最省事的方式是靜態方法 create(),它會一次完成建立與準備,直接回傳可用的物件:

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

第二個參數是資源 id。使用前必須在專案裡新增名為 raw 的資料夾,把音樂檔放進去,Android 便會自動產生對應的 R.raw.song。

播放、暫停與重來

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

這裡有個容易搞混的地方:第一次呼叫 start() 會從頭播起,但在 pause() 之後再呼叫 start(),是從暫停的位置續播。想真正回到開頭,得先 reset():

mediaPlayer.reset();

常用方法

方法說明
isPlaying()回傳是否正在播放。
seekTo(int ms)跳到指定毫秒位置,快轉快退的核心。
getCurrentPosition()目前播放位置(毫秒)。
getDuration()總時長(毫秒)。
reset()重設播放器狀態。
release()釋放所有持有的資源。
setVolume(float, float)設定左右聲道音量(0.0~1.0)。
setLooping(boolean)是否循環播放。
prepareAsync()非同步準備,網路來源時必用。

範例:可播放、暫停、快轉與快退的播放器

由於要實際聽到聲音,建議把 App 跑在真機上。

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

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 會先跳出視窗,讓你選擇要把 App 跑在哪裡:

選擇執行目標裝置

選好裝置後,手機上會出現播放器的初始畫面:

播放器預設畫面

此時暫停鈕是 disabled 的灰色狀態。按下播放鈕後,兩顆按鈕的可用狀態對調,時間與進度條開始推進:

播放中的狀態

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

暫停提示訊息

再按播放,音樂從暫停處續播而非回到開頭。按快轉或快退可前後跳 5 秒;當快轉已達曲尾時再按,就會看到提示訊息:

無法繼續快轉的提示

切換到其他 App 時,音樂仍會在背景持續播放,要讓它停下就得回到這個 App 並結束它。

product ion 等級還要補三件事:第一,範例用 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