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

Android 多媒體播放:MediaPlayer 的播放、暫停與進度控制

編輯:Android 開發實例

Android 提供多種播放音訊與影片的方式,而其中最基礎、也最廣泛被使用的一條路徑,就是 MediaPlayer 類別。它能播放本機檔案、應用程式內的資源,也能處理網路串流。

用 create() 建立播放器

MediaPlayer 提供靜態的 create() 方法,呼叫後即可取得物件實例:

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

第二個參數指定要播放的資源。這裡的 R.raw.song 代表專案中的 res/raw 目錄;如果還沒有這個資料夾,請自行建立並把音樂檔放進去。

播放、暫停與重設

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

start() 會開始(或從頭)播放。若先呼叫 pause() 再呼叫 start(),播放會從暫停處接續,而不是回到開頭。想要真正回到歌曲起點,得呼叫 reset():

mediaPlayer.reset();

除此之外,MediaPlayer 還有這些常用方法:

方法說明
isPlaying()回傳布林值,表示目前是否正在播放
seekTo(int position)把播放位置跳到指定的毫秒數
getCurrentPosition()回傳目前的播放位置(毫秒)
getDuration()回傳整段媒體的總時長(毫秒)
reset()把播放器重設回初始狀態
release()釋放 MediaPlayer 占用的所有資源
setVolume(float leftVolume, float rightVolume)設定左右聲道音量
setDataSource(FileDescriptor fd)設定音訊/影片的資料來源
selectTrack(int index)依索引選取指定軌道
getTrackInfo()回傳軌道資訊陣列

實作範例:功能完整的播放器

這個範例實作一個能播放、暫停、前跳與後跳 5 秒,並以 SeekBar 顯示即時進度的播放器。

步驟說明
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,選擇真機或模擬器安裝並驗證結果

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

版面配置 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/testsView2"
        android:layout_toRightOf="@+id/testsView1" />

    <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/testsView3"
        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/testsView3"
        android:src="@drawable/ic_launcher" />

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

字串資源 res/values/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 手機連上電腦,在 IDE 中開啟 Activity 檔並點擊執行鈕 執行,會先跳出視窗讓你選擇執行位置:

選擇執行裝置

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

播放器初始畫面

一開始暫停鈕不可用。按下播放鈕後,兩顆按鈕的可用狀態會互換:

播放中,暫停鈕轉為可用

音樂持續播放中,按下暫停鈕會看到暫停提示:

暫停播放的提示訊息

再次按下播放鈕,歌曲會從暫停處續播。此時按快轉或倒轉可前後跳 5 秒;若已達歌曲結尾,就會跳出無法繼續快轉的提示:

已達結尾無法快轉

即使切去處理其他事情,音樂仍會在背景繼續播放;要徹底停止,得把這個 App 從背景關閉。從資源管理的角度,正式專案應在 Activity 銷毀時呼叫 release(),並考慮用前景服務(Foreground Service)來維持背景播放,這也是 Android 8.0 以後的強制要求。

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