編輯:Android 開發實例
Android 在媒體播放這件事上提供了不少API,而最常被拿來入門的就是 MediaPlayer。它是內建媒體播放服務的 Java 層入口,音訊、視訊、串流都能處理。本文完整走過一次:從建立物件、播放暫停,到用 Handler 同步進度條,再到快轉碰到結尾時的邊界處理。
使用 MediaPlayer 最簡單的方式是呼叫靜態方法 create(),它會回傳一個已經完成準備的實例:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是要播放的媒體資源名稱。你需要在專案底下新增一個名為 raw 的資料夾,再把音樂檔放進去。相較於 assets,raw 會自動產生資源 ID,取用上省事許多。
mediaPlayer.start(); mediaPlayer.pause();
呼叫 start() 時音樂從頭開始播。若是在 pause() 之後再次呼叫 start(),音樂會從被停住的地方續播,而不是回到開頭——這是使用者期待的行為,也是「暫停」與「停止」的分野。
若你想強制回到起點,必須呼叫 reset():
mediaPlayer.reset();
但要注意,reset() 會把播放器退回未初始化的狀態,之後必須重新設定資料源並準備,不能直接 start()。單純想回到開頭播放,seekTo(0) 加上 start() 才是對的做法。
isPlaying():回傳 true/false,表示目前是否正在播放。seekTo(int position):傳入毫秒數,把播放位置移到該處。getCurrentPosition():回傳目前的播放位置(毫秒)。getDuration():回傳整段媒體的總長度(毫秒)。reset():重設媒體播放器。release():釋放 MediaPlayer 物件持有的所有資源。setVolume(float leftVolume, float rightVolume):設定左右聲道音量。setDataSource(FileDescriptor fd):以檔案描述項設定音訊/視訊來源。selectTrack(int index):選取列表中指定索引的軌道。getTrackInfo():回傳軌道資訊的陣列。這個範例建立一個基本的媒體播放器,可以前進、後退、播放與暫停,並以 SeekBar 即時顯示進度。由於要聽實際聲音,建議使用真機測試。
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/textView1" />
<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/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/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/textView3"
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>
假設你已將實機 Android 手機連上電腦。要從 Eclipse 執行,開啟專案其中一個 Activity 檔,點擊工具列上的執行圖示:
啟動應用程式前,Eclipse 會顯示一個視窗讓你選擇要執行在哪裡:
選擇你的手機作為選項,然後看著裝置畫面出現預設的播放介面:
預設會看到暫停鈕是 disabled 的狀態。按下播放鈕後,它自己變成 disabled,暫停鈕則轉為 enable:
到目前為止音樂一直在播放。現在按下暫停鈕並觀察暫停提示:
再按播放鈕,歌曲不會從頭開始,而是從剛才暫停的位置繼續。接著按快轉或回退鈕,每次跳 5 秒。當歌曲快播完而無法再往前跳時,會出現類似這樣的提示:
當你在手機上做其他事情時,音樂會持續在背景播放。要讓它停下來,得把這個應用程式從背景活動中結束。
範例用 Handler.postDelayed() 每 100 毫秒更新一次時間,這個間隔足以讓進度條看起來平順,又不會造成明顯負擔;但別忘了在 Activity 銷毀時 removeCallbacks(),否則會有一個看不見的 Runnable 持續被觸發。
另外,範例中的 seekbar.setClickable(false) 讓使用者無法拖動進度條。若要開放拖曳,應該改用 OnSeekBarChangeListener,在 onStopTrackingTouch() 時才呼叫 seekTo(),避免拖動過程中被大量 seek 呼叫卡住。
最後,把播放邏輯寫在 Activity 內意味著螢幕一旋轉,播放狀態就歸零。正式產品請把控制交給 MediaSessionService,並在 onDestroy() 中確實呼叫 release(),否則硬體解碼器不會被釋放,連續切換頁面後可能出現播放不出聲音的狀況。
Android 補間動畫入門:縮放、旋轉與淡入淡出一次學會
Android 上的動畫方案不少,其中最簡單也最廣泛使用的莫過於補間動畫(Tween Animation)。你只需要給定起始值、結束值、尺寸、時間長度、旋轉角度等參數,系
Android WebView 支持 HTML5 Video 全屏播放的關鍵配置與代碼
讓 WebView 裡的 video 標籤能正常播放,需要硬件加速;讓它能全屏,需要攔截 WebChromeClient 的兩個回調。這兩步聽起來簡單,但中間有幾個容易讓
Android 登入畫面實作教學:帳號驗證、錯誤次數與安全性
登入畫面常用來驗證使用者身份。設計時除了帳號與密碼欄位,也要考慮錯誤提示、嘗試次數限制與安全性。 介面設計 使用兩個輸入框分別接收使用者名稱與密碼,密碼欄位需設定為密碼輸
AutoCompleteTextView 自動完成實作:單行與多行建議輸入
當使用者在可編輯文字欄位中打字時,若 App 能即時給出建議清單,輸入效率與正確率都會明顯提升。Android 為此提供了 AutoCompleteTextView:建議