編輯:Android 開發實例
Android 提供了許多方法來控制音訊/視訊檔案與串流的播放,而其中最根本的一個入口,就是名為 MediaPlayer 的類別。它讓你能以純 Java 的方式存取系統內建的媒體播放服務。本文除了說明基本操作,也會把焦點放在許多人忽略的「狀態機」概念上——理解狀態,才能避免呼叫時機錯誤造成的崩潰。
Android 提供的 MediaPlayer 類別可存取內建的媒體播放器服務,例如播放音訊、視訊等。為了使用 MediaPlayer,我們要呼叫這個類別的靜態 create() 方法,它會回傳 MediaPlayer 類別的一個實例。語法如下:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是要播放的歌曲名稱。必須先在專案下建立一個名為 raw 的新資料夾,然後把音樂檔放進去。
建立了 MediaPlayer 物件之後,可以呼叫一些方法來啟動或停止音樂:
mediaPlayer.start(); mediaPlayer.pause();
在呼叫 start() 時,音樂將從頭開始播放。如果此方法是在 pause() 之後再次被呼叫,音樂會從被停住的地方開始,而不是從頭開始。
要讓音樂從一開始啟動,必須呼叫 reset() 方法。語法如下:
mediaPlayer.reset();
這裡有個容易踩的雷:reset() 之後播放器回到 Idle 狀態,你無法直接 start(),必須重新設定資料源並準備完成。單純想重播同一首歌,seekTo(0) 才是對的工具。
除了 start 和 pause 方法,此類還提供了其他方法以便更好地處理音訊/視訊檔案:
isPlaying():這個方法只回傳 true/false,表示是否正在播放歌曲。seekTo(int position):此方法接受一個整數,把歌曲移到特定的毫秒位置。getCurrentPosition():這個方法回傳歌曲目前的播放位置,單位為毫秒。getDuration():這個方法回傳歌曲的總持續時間,單位為毫秒。reset():此方法重設媒體播放器。release():此方法釋放附屬於 MediaPlayer 物件的任何資源。setVolume(float leftVolume, float rightVolume):此方法設定了這個播放器的左右聲道音量。setDataSource(FileDescriptor fd):此方法設定音訊/視訊檔案的資料源。selectTrack(int index):此方法接受一個整數,並從列表中選取該特定索引的軌道。getTrackInfo():這個方法回傳軌道資訊的陣列。這是官方文件裡最重要、卻最常被跳過的一張觀念圖。簡化後的合法路徑是:Idle → Initialized → Prepared → Started → Paused / Stopped → End。在錯誤的狀態呼叫錯誤的方法,你會收到 IllegalStateException。幾個實務守則:
create() 已幫你完成 Initialized 與 Prepared,可以直接 start();但若用 setDataSource() 自行設定來源,就必須顯式呼叫 prepare()(或 prepareAsync() 搭配 OnPreparedListener)。pause() 只能從 Started 狀態呼叫;在 Prepared 狀態呼叫會炸掉。stop() 之後不能 start(),必須重新 prepare()。reset() 再重新準備。這裡示範如何使用 MediaPlayer 類別。它建立一個基本的媒體播放器,可以前進、後退、播放和暫停歌曲。為了試驗這個範例,需要在實機上執行以聽到實際聲音。
com.yiibai.mediaplayer 之下。建立專案時確認 Target SDK 與 Compile With 都設在最新版本的 Android SDK,以便使用更高層級的 API。src/MainActivity.java 加入 MediaPlayer 程式碼。res/layout/activity_main.xml 加入對應的 XML 元件。res/values/string.xml 加入必要字串元件。raw 的新資料夾,並放入名為 song.mp3 的音樂檔。主活動 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/textV8iew2"
android:layout_toRightOf="@+id/textV8iew1" />
<TextView android:id="@+id/textV8iew1"
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/textV8iew2"
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/textV8iew3"
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/textV8iew3"
android:src="@drawable/ic_launcher" />
<TextView android:id="@+id/textV8iew4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textV8iew3"
android:layout_alignBottom="@+id/textV8iew3"
android:layout_toRightOf="@+id/imageButton1"
android:text="TextView" />
</RelativeLayout>
字串 res/values/strings.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>
試著執行你的 MediaPlayer 應用程式。這裡假設你已將實機 Android 手機連上電腦。要從 Eclipse 執行 App,開啟專案其中一個 Activity 檔並點擊工具列上的執行圖示:
在啟動應用程式之前,Eclipse 會顯示一個視窗,讓你選擇要把 Android 應用程式執行在哪裡。
選擇你的行動裝置作為選項,然後查看手機,它會顯示你的預設畫面:
預設你會看到暫停鈕是 disabled 的。現在按播放鈕,它會變成 disabled 而暫停鈕轉為 enable,如下圖:
直到現在,音樂一直在播放。現在按暫停鈕並觀察暫停提示,如下圖:
現在再按播放鈕,歌曲不會從頭開始,而是從剛才暫停的位置續播。接著按快轉或後退鈕,讓歌曲往前或往後跳 5 秒。當歌曲接近結尾而無法再往前跳時,會出現類似這樣的提示:
當你在手機上執行其他任務時,音樂會持續在背景播放。要讓它停下來,必須把這個應用程式從背景活動中結束。
範例把 forwardTime 與 backwardTime 都設為 5000(毫秒)。想改成 15 秒跳轉,只要把這兩個值改為 15000 即可,其餘邏輯不用動——這正是把魔法數字抽成具名常數的價值。同時也建議把提示訊息中的「5 seconds」改為由常數插值產生,否則改了行為卻沒改文案,會讓使用者困惑。
最後提醒:這個範例沒有覆寫 onDestroy(),因此離開 App 後 MediaPlayer 仍佔著解碼器資源。正式專案務必在 Activity 銷毀時呼叫 release() 並清除 Handler 的回呼,否則反覆進入播放頁幾次之後,就會出現明明按下播放卻沒有聲音的狀況。
Web App 與原生 App 的差異與選擇
在移動產品開發中,HTML5 封裝的 Web App 與原生 App 各有適用場景。兩者最大的差異在於執行方式、能力邊界與使用者體驗。功能與體驗差異HTML5 適合輕量頁
Android 本地化入門:讓 App 跟著語系切換文字
Android App 常需要在不同語言環境下顯示不同文字。Android 的資源系統會依裝置語言自動選擇對應的 values 目錄,因此只要準備好各語言的 string
Android 自定義軟鍵盤:打造中文與數字輸入鍵盤
軟鍵盤的核心類別 Android 自定義軟鍵盤主要使用 Keyboard 與 KeyboardView。Keyboard 描述按鍵排列,KeyboardView 負責繪製
在 Android 中解析 JSON:從語法到天氣查詢實作
行動裝置上的資料,大多以 JSON 的形式從伺服器流過來。它源自 JavaScript 的物件寫法,卻早已成為語言中立的通用格式,憑著結構清爽、可讀性高,逐步取代 XML