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

從零開始學 Android:用 MediaPlayer 播放 MP3

編輯:Android 技術基礎

打造簡單音樂播放器

Android 的 MediaPlayer 同時支援音訊與影片播放。本篇以 MP3 為例,示範播放、暫停、停止與播放完成處理。

準備素材

將 play.png、pause.png、stop.png 放入 res/drawable-hdpi。

再將 coffee.mp3 放入 res/raw。

介面配置

activity_main.xml 中放入三個 ImageButton 與一個 TextView。

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

    <ImageButton
        android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/play" />

    <ImageButton
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/pause" />

    <ImageButton
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/stop" />

    <TextView
        android:id="@+id/prompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提示信息" />
</LinearLayout>

程式實作

使用 MediaPlayer.create(this, R.raw.coffee) 建立播放器。播放時先 stop 再 prepare/start,避免重複播放造成狀態錯誤。暫停與停止可透過 isPaused 變數切換。

mpPlayer = MediaPlayer.create(this, R.raw.coffee);
if (mpPlayer != null) {
    mpPlayer.stop();
}
mpPlayer.prepare();
mpPlayer.start();
tvPrompt.setText("音樂播放中...");

暫停與繼續:

if (isPaused == false) {
    mpPlayer.pause();
    isPaused = true;
} else {
    mpPlayer.start();
    isPaused = false;
}

播放完成與錯誤時,記得釋放資源。

mpPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        mp.release();
        tvPrompt.setText("音樂播放結束!");
    }
});

執行結果

點擊播放,即可聽見 res/raw 中的音樂。

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