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

Android MediaPlayer 完整教學:播放控制、進度條與背景播放的界線

編輯:Android 開發實例

MediaPlayer 是 Android 內建的媒體播放類別,能處理本機檔案、raw 資源與網路串流。它 API 不多、上手極快,但正因為簡單,很多人忽略它在背景播放與資源釋放上的限制。本章從基本控制講到一個功能完整的播放器範例,最後談談那些界線。

建立與播放

最簡便的方式是靜態 create(),它會完成載入與準備:

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

第二個參數是資源 ID,因此音樂檔要放在 res/raw 資料夾。播放與暫停:

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

start() 第一次是從頭播,暫停後再呼叫則從中斷處續播。若一定要回到開頭,先 reset():

 mediaPlayer.reset();

方法速查

方法說明
isPlaying()回傳是否正在播放。
seekTo(int position)跳到指定毫秒位置。
getCurrentPosition()目前位置(毫秒)。
getDuration()總長度(毫秒)。
reset()重設播放器。
release()釋放 MediaPlayer 資源。
setVolume(float, float)設定左右声道音量。
setDataSource(FileDescriptor)指定資料來源。
selectTrack(int index)選取指定軌道。
getTrackInfo()取得軌道資訊陣列。

範例:能聽、能跳、能暫停的播放器

步驟要做的事
1用 Android Studio 建立 MediaPlayer 專案,套件名 com.yiibai.mediaplayer。
2修改 MainActivity.java 加入播放控制與進度更新。
3修改 activity_main.xml 加入四顆 ImageButton 與 SeekBar。
4修改 res/values/string.xml。
5新增 res/raw 資料夾,放入 song.mp3。
6用真機執行並確認聲音輸出。

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.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.textV4); startTimeField = (TextView)findViewById(R.id.textV1); endTimeField = (TextView)findViewById(R.id.textV2); 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_alignParentBottom="true" android:onClick="forward" android:src="@android:drawable/ic_media_ff" /> <ImageButton android:id="@+id/imageButton1" android:layout_toRightOf="@id/imageButton3" android:onClick="play" android:src="@android:drawable/ic_media_play" /> <ImageButton android:id="@+id/imageButton2" android:layout_toRightOf="@id/imageButton1" android:onClick="pause" android:src="@android:drawable/ic_media_pause" /> <ImageButton android:id="@+id/imageButton4" android:layout_toRightOf="@id/imageButton2" android:onClick="rewind" android:src="@android:drawable/ic_media_rew" /> <SeekBar android:id="@+id/seekBar1" android:layout_above="@id/imageButton3" /> <TextView android:id="@+id/textV1" android:text="@string/inital_Time" android:layout_alignTop="@id/seekBar1" /> <TextView android:id="@+id/textV2" android:text="@string/inital_Time" android:layout_alignTop="@id/seekBar1" android:layout_alignParentRight="true" /> <TextView android:id="@+id/textV3" android:text="@string/hello_world" /> <TextView android:id="@+id/textV4" android:layout_alignBaseline="@id/textV3" android:layout_toRightOf="@id/imageButton1" /> </RelativeLayout>

string.xml 與 manifest:

 <resources> <string name="app_name">MediaPlayer</string> <string name="hello_world">Now Playing:</string> <string name="inital_Time">0 min, 0 sec</string> </resources>

<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.mediaplayer"> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

執行畫面

接上真機,按下工具列的執行 鈕,並選擇要安裝的裝置:

App 啟動後,暫停鈕預設是停用狀態:

按下播放,兩顆按鈕的啟用狀態互換,音樂開始,SeekBar 同步前進:

按下暫停,出現暫停提示:

再次播放會從暫停處續播;一路快轉到尾聲時,則會提示無法再往前跳 5 秒:

最後談談界線。範例中的音樂會在 App 退到背景後繼續播放,這是因為播放服務並沒有跟著 Activity 一起停下來。若你做的是「離開畫面就該停」的播放器,請在 onPause() 或 onStop() 裡明確暫停;若你希望它像音樂 App 一樣在通知列繼續運作,就該改用前景服務(Foreground Service)搭配通知,並在 onDestroy() 中呼叫 release() 釋放資源。這兩種設計都合理,但必須是你有意識的選擇,而不是預設行為。

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