編輯:Android 開發實例
Android 在音訊與影片播放上提供了不少 API,而 MediaPlayer 是最常被直接使用的一個。它把底層播放服務包成單一物件,讓你透過幾個方法就能控制播放、暫停、跳轉與音量。
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
create() 是靜態方法,會回傳一個已載入媒體、可直接播放的實體。第二個參數指定媒體來源;若是 App 內附檔案,需在專案裡建立名為 raw 的資料夾並把檔案放進去。
mediaPlayer.start(); mediaPlayer.pause(); mediaPlayer.reset();
start() 開始播放,若目前處於暫停,會從暫停點續播;reset() 則把播放器退回初始狀態,之後必須重新指定資料來源。這兩者的差異是自作播放器時最常搞混的地方。
| 方法 | 說明 |
|---|---|
isPlaying() | 回傳是否正在播放。 |
seekTo(int position) | 跳到指定的播放位置。 |
getCurrentPosition() | 取得目前播放位置(毫秒)。 |
getDuration() | 取得媒體總長度(毫秒)。 |
reset() | 重設媒體播放器。 |
release() | 釋放播放器占用的資源。 |
setVolume(float left, float right) | 設定左右声道音量。 |
setDataSource(FileDescriptor fd) | 指定媒體資料來源。 |
selectTrack(int index) | 選取指定索引的軌道。 |
getTrackInfo() | 回傳軌道資訊陣列。 |
做一個能播放、暫停、快轉、快退的播放器,並搭配 SeekBar 顯示進度。因為需要實際聽到聲音,請在真機上測試。
| 步驟 | 做法 |
|---|---|
| 1 | 建立 Android 專案 MediaPlayer,套件名 com.example.mediaplayer,Target SDK 與 Compile With 使用較新版本。 |
| 2 | 修改 src/MainActivity.java,加入 MediaPlayer 程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,加入 XML 元件。 |
| 4 | 修改 res/values/string.xml,加入字串資源。 |
| 5 | 新增 raw 資料夾並放入 song.mp3。 |
| 6 | 執行 App,選擇已連線的裝置並驗證結果。 |
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;
}
}
進度同步的做法是:用 Handler.postDelayed() 每 100 毫秒回讀一次 getCurrentPosition(),更新時間文字與 SeekBar。這個間隔在流暢度與耗電之間算是合理的折衷。
<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>
<?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>
<?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>
把真機連上電腦,開啟 Activity 檔案後按下工具列的執行鈕:
接著選擇要安裝的目標裝置:
選好裝置後,畫面呈現播放器初始狀態:
按下播放鈕,播放鈕變灰、暫停鈕啟用:
按下暫停鈕,會看到對應提示,音樂停止:
再按播放會從暫停處續播。試著按快轉或快退各跳 5 秒;當再往前就會超出總長度時,程式會跳出提示:
切換到其他 App 時,這個播放器的音樂仍會在背景持續播放;要徹底停止,必須離開應用程式。在正式專案中,請於 Activity 的 onDestroy() 呼叫 release(),並依需求在 onPause() 處理暫停與否。若你的 App 需要在背景長時間播放音樂,更進一步應該改用 MediaSession 搭配前景服務(Foreground Service),並在通知列提供控制按鈕——這是符合現代 Android 規範的做法。
用 User Agent 正確分辨 Android 手機與平板的安全做法
隨著 Android 裝置數量暴增,愈來愈多網站需要針對它們做調整,而主流類型不外乎手機與平板。問題是:在適配時,該如何透過 User Agent(以下簡稱 UA)把兩者
Android 進階:打造手機模擬信號示波器
前面我們簡單介紹過 Android 開發中 AudioRecord 與 AudioTrack 的用法,這次結合 SurfaceView,動手做一個 Android 版的手
Android ApiDemo 系列八:Hello World 置中顯示
ApiDemo 中的 Hello World 範例看似簡單,卻能說明 Android 版面配置中常見的對齊概念。此範例的 TextView 使用 match_parent
Android 登入頁面設計:帳密輸入、錯誤提示與嘗試次數控制
登入頁是使用者對一支 App 的第一印象,也是安全防線的第一關。它要做的事看似簡單——收帳號、收密碼、比對——但細節決定成敗:密碼不能被旁人看光、錯誤要講得清楚、盲猜的次