編輯:Android 開發實例
要在 Android 上播放音訊或影片,最直接的方式就是使用 MediaPlayer 類別。它是系統內建媒體播放服務的 Java 介面,音訊、影片、串流都吃得住,同時 also 提供了播放、暫停、跳轉、調整音量等一整套控制方法。
建立播放器的標準寫法是呼叫靜態方法 create(),它會回傳一個 MediaPlayer 實體:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數指定要播放的資源。使用這個寫法時,必須先在專案裡新增一個名為 raw 的資料夾,把音樂檔放進去。
有了物件之後,就能用下列方法控制播放:
mediaPlayer.start(); mediaPlayer.pause();
start() 會從頭開始播放;若中途呼叫過 pause(),再次 start() 會從暫停的位置續播,而不是回到開頭。想真正回到起點,得呼叫 reset():
mediaPlayer.reset();
除了這三個基本方法,類別還提供了不少好用的 API:
| 編號 | 方法 | 說明 |
|---|---|---|
| 1 | isPlaying() | 回傳布林值,表示目前是否正在播放。 |
| 2 | seekTo(position) | 跳到指定的播放位置(毫秒)。 |
| 3 | getCurrentPosition() | 取得目前的播放位置(毫秒)。 |
| 4 | getDuration() | 取得整首曲子的總長度(毫秒)。 |
| 5 | reset() | 重設播放器狀態。 |
| 6 | release() | 釋放 MediaPlayer 佔用的資源。 |
| 7 | setVolume(left, right) | 設定左右聲道音量。 |
| 8 | setDataSource(FileDescriptor fd) | 指定音訊/影片的資料來源。 |
| 9 | selectTrack(int index) | 選取指定索引的軌道。 |
| 10 | getTrackInfo() | 回傳軌道資訊陣列。 |
這個範例會做出一個完整的播放介面:播放/暫停切換、前後跳 5 秒、進度條同步更新,並以 Toast 提示操作結果。由於要真的聽到聲音,建議用實機測試。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Eclipse 建立 Android 專案,套件名稱 com.yiibai.mediaplayer,Target SDK 與 Compile With 選最新版本。 |
| 2 | 修改 src/MainActivity.java,加入 MediaPlayer 相關程式碼。 |
| 3 | 修改 res/layout/activity_main.xml 加入版面元件。 |
| 4 | 修改 res/values/string.xml 加入字串資源。 |
| 5 | 在專案下新增 raw 資料夾,放入名為 song.mp3 的音樂檔。 |
| 6 | 執行應用程式並在裝置上驗證。 |
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;
}
}
<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/textView2"
android:layout_toRightOf="@+id/textView1" />
<TextView android:id="@+id/textView1"
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/textView3"
android:src="@drawable/ic_launcher" />
<TextView android:id="@+id/textView4"
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>
<?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>
假設已用 USB 把 Android 手機連上電腦。在 Eclipse 中開啟任一 Activity 檔,點擊工具列上的執行按鈕:
Eclipse 會先跳出視窗,讓你選擇要執行在哪個裝置上:
選好你的手機,畫面上會出現播放介面:
初始狀態暫停鈕是灰的。按下播放後,播放鈕變灰、暫停鈕亮起:
音樂持續播放中,按下暫停會看到對應的 Toast 提示:
再按一次播放,曲子會從剛剛暫停的地方繼續,而不是從頭開始。此時若按快轉或倒轉,可前後跳 5 秒;一旦已經快轉到接近結尾,就會看到「無法再往前跳」的提示:
最後要注意:當你切到其他工作時,音樂仍會在背景繼續播放。要讓它停下來,得回到這個應用程式並結束它。
Android Spinner 下拉框的靜態與動態兩種用法實戰
Spinner 相當於原生的下拉選擇框,位於 android.widget 包下,同時也是 View 的子類。它平時只展示當前選中項,點擊後才展開列表供用戶挑選,列表元素
Android 本地化實作:依語言環境切換字串資源
當 App 要面對不同語言的市場時,本地化是必要步驟。Android 透過資源資料夾的命名規則,讓系統自動選擇最適合的語言資源。 字串資源 預設字串放在 res/valu
Android 應用本地化:讓 App 輕鬆支援多語言與地區
Android 應用往往運行在name不同國家、不同語言環境的裝置上。若希望 App 真正做到「在地化」,就必須讓文字、數字、日期與檔案等资源都能依裝置的語言環境自動切換
Android 單元測試實例分析:從設定到執行
本文以實例說明 Android 單元測試的用法。在實際開發中,撰寫 Android 軟體的過程需要不斷測試,而 JUnit 測試框架正是正規開發必備的技術。透過 JUni