編輯:Android 開發實例
Android 提供了多種播放音訊與影片的方式,而最直接、最常被拿出來用的是 MediaPlayer 這個類別。它包裝了底層的媒體播放服務,讓你只要幾行程式碼就能播放放在應用程式內、SD 卡上,或是串流而來的音樂。
最簡單的做法是呼叫靜態方法 create(),它會直接幫你準備好一個可以播放的實體:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是媒體資源。若要播放的是打包在 App 裡的檔案,必須先在專案底下新增一個名為 raw 的資料夾,把音樂檔放進去(例如 song.mp3)。放在 raw 的好處是 Android 不會對它做額外壓縮,適合音訊素材。
mediaPlayer.start(); mediaPlayer.pause();
start() 會開始播放;如果目前是暫停狀態,則會從暫停的位置繼續,而不是回到開頭。若你希望每次播放都從頭開始,必須先呼叫:
mediaPlayer.reset();
reset() 會把播放器退回初始狀態,之後需要重新設定資料來源才能再播放。
| 方法 | 說明 |
|---|---|
isPlaying() | 回傳 true/false,表示目前是否正在播放。 |
seekTo(int position) | 把播放位置跳到指定的毫秒數。 |
getCurrentPosition() | 取得目前的播放位置,單位為毫秒。 |
getDuration() | 取得整首曲子的總長度,單位為毫秒。 |
reset() | 把媒體播放器重設為初始狀態。 |
release() | 釋放播放器持有的所有資源,必須呼叫以免記憶體浪費。 |
setVolume(float left, float right) | 分別設定左右聲道的音量,範圍為 0.0 到 1.0。 |
setDataSource(FileDescriptor fd) | 指定要播放的音訊或影片資料來源。 |
selectTrack(int index) | 在多軌媒體中選取指定索引的軌道。 |
getTrackInfo() | 回傳一個陣列,內容為各軌道的資訊。 |
接下來做一個功能完整的播放器介面:顯示歌曲名稱與播放時間、有播放/暫停按鈕、一條可顯示進度的 SeekBar,以及快轉與快退各 5 秒的按鈕。
由於要實際聽到聲音,建議在真機上測試。
| 步驟 | 做法 |
|---|---|
| 1 | 在 Android Studio 建立專案,命名為 MediaPlayer,套件名稱使用 com.example.mediaplayer,Target SDK 與 Compile With 設為較新版本。 |
| 2 | 修改 src/MainActivity.java,加入 MediaPlayer 的播放控制邏輯。 |
| 3 | 修改 res/layout/activity_main.xml,加入按鈕、SeekBar 與時間文字。 |
| 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 毫秒回讀一次播放位置,再更新時間文字與 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/textView2"
android:layout_toRightOf="@+id/textV8iew1" />
<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/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/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/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>
把真機以 USB 連上電腦,開啟任一 Activity 檔案後按下工具列上的執行鈕:
IDE 接著會詢問要把 App 裝到哪裡去:
選擇你的實機,畫面上會出現播放器的初始狀態:
此時暫停鈕是灰的。按下播放鈕後,播放鈕變灰、暫停鈕變可用:
音樂持續播放中,按下暫停鈕會看到提示訊息:
再次按下播放鈕,音樂會從剛才暫停的位置繼續,而不是回到開頭。接著可以試著按快轉或快退,每次跳 5 秒;當已經快到曲子尾聲、再跳就會超出長度時,程式會跳出提示:
這個範例的音樂在你切到其他 App 之後仍會在背景持續播放。要停止它,必須離開這個應用程式;而在正式專案裡,請務必在 Activity 的 onDestroy() 或 onPause() 中呼叫 mediaPlayer.release(),否則播放器占用的記憶體與硬體資源不會被釋放,長期下來容易引發問題。
Android JSON 剖析教學:JSONObject 與天氣資料
在 Android 開發中,JSON 解析是取得遠端資料的關鍵步驟。相較於 XML,JSON 更精簡,也更容易與 Web API 搭配。 先找出需要的欄位 解析前,先確認
Android 自訂輸入法 IME 開發教程
輸入法編輯器,又稱 IME,是 Android 中讓使用者輸入文字的元件。開發者可自訂軟鍵盤、語音輸入或其他輸入方式,並讓使用者在系統設定中選擇。 基本架構 自訂 IM
Android 記事本示例剖析(四):NoteEditor 類與 Content Provider 機制
在前一篇中,我們研究了 Activity 的生命週期、狀態轉換機制以及自定義控件。本文延續記事本示例的分析,重點拆解 NoteEditor 類與 Content Prov
TextView 寬度填滿時 Drawable 不居中?兩種解法與取捨
做專案時經常要「圖片 + 文字」並排顯示,一般情況下設定 DrawableLeft/Right/Top/Bottom 就好了。但有一個情況會出問題:當 TextView