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

Android MediaPlayer 教學:動手做一個音樂播放器

編輯:Android 開發實例

要在 App 裡播放音訊或影片,Android 提供了不少途徑,而最最直接的一條路就是 MediaPlayer 類別。它被封裝在 android.media 套件中,可以播放本機檔案、資源目錄裡的素材,也能處理網路串流。

本文會從最基本的播放與暫停講起,再逐步加上快轉、倒退、進度條與時間顯示,最後完成一個操作手感接近市面播放器的範例。

建立 MediaPlayer 物件

最省事的做法是呼叫靜態方法 create(),它會幫你把資源載入並準備好,直接回傳一個可用的實例:

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

第二個參數是音訊資源。使用前必須先在專案裡新增一個名為 raw 的資料夾(app/src/main/res/raw),把 song.mp3 放進去。放在 raw 的好處是 Android 不會對它做額外壓縮,音質較有保障。

播放與暫停

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

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

如果你希望「無論如何都從頭開始」,就必須先呼叫 reset():

mediaPlayer.reset();

其他常用方法

方法說明
isPlaying()回傳布林值,代表目前是否正在播放。
seekTo(int position)跳到指定的毫秒位置,快轉與倒退都靠它。
getCurrentPosition()取得目前播放位置,單位為毫秒。
getDuration()取得整首曲子的總長度,單位為毫秒。
reset()把播放器重設為初始狀態。
release()釋放 MediaPlayer 佔用的資源,Activity 銷毀時務必呼叫。
setVolume(float left, float right)分別設定左右聲道的音量,範圍 0.0 到 1.0。
setDataSource(FileDescriptor fd)指定音訊或影片的資料來源。
selectTrack(int index)選取特定索引的軌道。
getTrackInfo()回傳軌道資訊陣列。

實作:可快轉、可倒退的播放器

範例會用到四顆 ImageButton(播放、暫停、快轉、倒退)、一條 SeekBar,以及顯示目前時間與總長度的 TextView。快轉與倒退的步長設定為 5 秒。

由於要聽聲音,請務必在實機上測試。

步驟做法
1建立 Android 專案,命名為 MediaPlayer,套件名稱 com.yiibai.mediaplayer,Target SDK 選最新版本。
2修改 src/MainActivity.java,加入 MediaPlayer 相關邏輯。
3修改 res/layout/activity_main.xml,配置按鈕與進度條。
4修改 res/values/string.xml,補上字串資源。
5在專案下新增 raw 資料夾,放入名為 song.mp3 的音樂檔。
6執行 App,安裝到裝置上驗證。

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

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>

string.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 連上電腦。在 IDE 中開啟主要的 Activity 檔案,按下工具列上的執行按鈕:

IDE 會先跳出一個視窗,讓你選擇要執行在哪個目標上。

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

此時暫停鍵是 disabled 的灰色狀態。按下播放鍵後,播放鍵變灰、暫停鍵亮起:

音樂正在播放中。按下暫停鍵,會看到提示訊息,音樂停在目前的位置:

再次按播放鍵,曲子會從剛剛暫停的地方續播,而不是回到開頭。這段時間你可以按快轉或倒退鍵前後跳 5 秒;如果已經快轉到接近結尾、再往前就會超出總長度,程式會跳出提示:

最後要提醒的是,按 Home 鍵離開 App 之後音樂仍會在背景持續播放。若要真正停止,必須回到這個 App 並結束它,或是在 onPause/onStop 裡自行呼叫 pause()。正式上線的播放器通常會搭配前景服務(Foreground Service)與通知列控制,才能提供完整的背景播放體驗。

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