編輯:Android 開發實例
要在 Android 上播放音訊或影片,可以走不同的技術路線,但最經典、也最常被拿來入門的是 MediaPlayer。它被封裝在 android.media 套件中,作為系統媒體服務的代理,本機檔案、網路串流都能播。
最省事的方式是呼叫靜態的 create(),它會一口氣完成建立與載入:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是媒體來源。若要把音樂跟著 APK 一起打包,請在專案裡新增名為 raw 的資料夾並放入音樂檔;若檔案位於外部儲存空間或串流來源,則改用 setDataSource() 指定。
物件到手後,最常呼叫的兩個方法如下:
mediaPlayer.start(); mediaPlayer.pause();
行為細節值得記住:start() 在初始狀態下會從頭播;但若中途 pause() 過,再一次 start() 會從暫停點續播。想要強制回到開頭,得先呼叫 reset():
mediaPlayer.reset();
| 編號 | 方法 | 說明 |
|---|---|---|
| 1 | isPlaying() | 回傳目前是否正在播放。 |
| 2 | seekTo(int position) | 跳到指定毫秒位置,快轉與倒轉都靠它。 |
| 3 | getCurrentPosition() | 取得目前播放位置(毫秒)。 |
| 4 | getDuration() | 取得媒體總長度(毫秒)。 |
| 5 | reset() | 把播放器重設到初始狀態。 |
| 6 | release() | 釋放播放器持有的資源,離開前一定要呼叫。 |
| 7 | setVolume(float left, float right) | 設定左右声道音量,範圍 0 至 1。 |
| 8 | setDataSource(FileDescriptor fd) | 指定媒體資料來源。 |
| 9 | selectTrack(int index) | 依索引選取軌道。 |
| 10 | getTrackInfo() | 回傳軌道資訊陣列。 |
這個範例做出一個能播放、暫停、前跳 5 秒、後退 5 秒,並同步顯示時間與進度條的播放器。由於要聽聲音,建議用實機測試。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名 MediaPlayer,套件 com.yiibai.mediaplayer,Target SDK 與 Compile With 對齊最新版 SDK。 |
| 2 | 修改 src/MainActivity.java,實作 MediaPlayer 邏輯。 |
| 3 | 修改 res/layout/activity_main.xml,加入四顆 ImageButton、SeekBar 與時間文字。 |
| 4 | 修改 res/values/string.xml,加入字串資源。 |
| 5 | 在 res 下新增 raw 資料夾,放入 song.mp3。 |
| 6 | 執行 App,裝到裝置上驗證。 |
主活動 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.Button; import android.widget.EditText; 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) { // Inflate the menu; this adds items to the action bar if it is present. 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/textVew2" android:layout_toRightOf="@+id/textView1" /> <TextView android:id="@+id/textVew1" 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/textVew3" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textVew4" 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>
字串資源 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>
假設已用 USB 把實機連上電腦。開啟任一活動檔,點擊工具列上的執行鈕:
IDE 會跳出選擇視窗,讓你決定要跑在哪個目標上:
選定行動裝置後,裝置上會出現播放器的預設畫面:
此時暫停鈕為不可用狀態。按下播放鈕,兩顆按鈕的啟用狀態互換:
音樂正在播放,按下暫停會看到對應的提示:
再次按下播放,曲子從剛才的位置續播而非回到開頭。若持續按快轉直到超過總長,就會看到無法再往前跳的提示:
當你切換到其他 App,音樂仍會在背景持續播放;要徹底停止,得把這個 App 從後台移除。
這也說明了一個關鍵觀念:MediaPlayer 不會替你管理生命週期。請務必在 onPause() 暫停、在 onDestroy() 呼叫 release() 釋放資源,否則容易出現記憶體配置與「音樂關不掉」的問題。若想做成正式的背景播放體驗(含通知列控制、耳機按鍵),正確路徑是搭配 MediaSessionCompat 與前景服務。
用 Handler 讓 SeekBar 跟上音樂:Android MediaPlayer 進階實作
MediaPlayer 只負責「播放」這件事,它不會告訴使用者現在播到哪裡。要讓介面呈現流暢的播放進度,得自己定時去問它目前的位置,再把結果畫到 SeekBar 上。這就
Android MediaPlayer(多媒體播放):音訊與影片控制入門
Android 提供了許多方法來控制播放的音訊/影片檔案與串流,其中主要的一種是透過名為 MediaPlayer 的類別。 MediaPlayer 類別讓 Android
Android 圖片特效四連發:縮放、圓角、倒影與 Drawable 轉 Bitmap
清單、卡片、商品列表裡常需要一點視覺裝飾——縮圖要縮放、頭像要圓角、橫幅要倒影。這些效果在 Android 裡全靠 Bitmap 搭配 Canvas、Matrix、Pai
用 JSONObject 解析天氣 API 回傳的 JSON 資料
行動 App 的資料大多來自遠端伺服器,而 JSON 是目前最主流的傳輸格式。它的名稱源自 JavaScript Object Notation,但格式本身與語言無關,任