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

Android MediaPlayer 完整指南:播放控制、進度條與快轉倒轉

編輯:Android 開發實例

要在 App 裡播放音訊或影片,Android 提供了不少途徑,而 MediaPlayer 是最直覺的一個。它讓你以幾行程式碼就能控制內建媒體播放服務,完成播放、暫停、跳轉等基本操作。

初始化播放器

使用靜態的 create() 方法建立物件,它會回傳一個已準備好的 MediaPlayer 實例:

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

第二個參數指向媒體資源。你需要先在專案下建立名為 raw 的資料夾,並把音樂檔放進去。

播放與暫停的差別

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

第一次呼叫 start() 會從頭播放;而在 pause() 之後再呼叫 start(),會從暫停處續播。若一定要回到開頭,必須先呼叫 reset():

 mediaPlayer.reset();

常用方法整理

  • isPlaying():回傳是否正在播放。
  • seekTo(position):跳至指定毫秒位置。
  • getCurrentPosition():目前播放位置(毫秒)。
  • getDuration():媒體總長度(毫秒)。
  • reset():重設播放器狀態。
  • release():釋放播放器持有的資源。
  • setVolume(float leftVolume, float rightVolume):設定左右声道音量。
  • setDataSource(FileDescriptor fd):指定媒體資料來源。
  • selectTrack(int index):依索引選取軌道。
  • getTrackInfo():回傳軌道資訊陣列。

特別說明 release():MediaPlayer 會佔用原生資源,忘記釋放容易造成記憶體不足或其他播放器無法取得音訊焦點。實務上應在 Activity 的 onDestroy() 中呼叫。

範例:四顆按鈕的簡易播放器

操作步驟:

  1. 用 Android Studio 建立專案,命名 MediaPlayer,套件 com.yiibai.mediaplayer,Target SDK 與 Compile With 選最新版本。
  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;
   }
}

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/textViem1" />

   <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/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textViem3"
      android:layout_alignBottom="@+id/textView3"
      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>

將實體裝置連上電腦,在 Eclipse 中開啟 Activity 檔並點擊執行 ,Eclipse 會先詢問要執行到哪個目標。

選擇你的手機,裝置上會顯示播放器主畫面:

預設暫停鈕為停用狀態。按下播放鈕後兩顆按鈕的啟用狀態會互換:

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

再次按播放鈕時,音樂從暫停處續播而非回到開頭。此時按快轉或倒轉可前後跳 5 秒,若已無 Enough 空間可跳,就會顯示提示訊息:

最後提醒:這個範例的音樂會在背景持續播放,即使切換到其他 App。要停止它,必須回到本應用程式結束播放,或在生命週期方法中確實呼叫 pause() 與 release()。

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