編輯:Android 開發實例
Android 播放音訊與影片的方式有好幾種,MediaPlayer 是最容易上手的一個。它位於 android.media 套件,除了本機檔案與 res/raw 資源,也能播放網路串流。
本文的目標很明確:做出一個具備播放、暫停、快轉 5 秒、倒退 5 秒與即時進度顯示的播放器。
最簡便的方式是靜態方法 create(),它會完成載入與準備,直接回傳可用實例:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是音訊資源,使用前請在 res 底下新增名為 raw 的資料夾,把音樂檔放進去。raw 裡的檔案不會被 build 流程二次壓縮,適合放對音質有要求的素材。
mediaPlayer.start(); mediaPlayer.pause();
start() 首次呼叫時從頭播放,暫停後再呼叫則從中斷處續播。若無論如何都要回到開頭,得先呼叫 reset():
mediaPlayer.reset();
| 方法 | 說明 |
|---|---|
| isPlaying() | 回傳是否正在播放。 |
| seekTo(int position) | 跳到指定毫秒位置,快轉與倒退的核心。 |
| getCurrentPosition() | 目前播放位置(毫秒)。 |
| getDuration() | 總長度(毫秒)。 |
| reset() | 重設播放器狀態。 |
| release() | 釋放資源,Activity 銷毀時別忘了呼叫。 |
| setVolume(float left, float right) | 設定左右声道音量(0.0~1.0)。 |
| setDataSource(FileDescriptor fd) | 指定資料來源。 |
| selectTrack(int index) | 選取指定索引的軌道。 |
| getTrackInfo() | 回傳軌道資訊陣列。 |
畫面上有四顆 ImageButton 分別負責播放、暫停、快轉與倒退,一條 SeekBar 顯示進度,兩個 TextView 顯示目前時間與總時長。前進與後退的步長都設為 5000 毫秒。
請在實機上測試,模擬器不一定有音效輸出。
| 步驟 | 做法 |
|---|---|
| 1 | 建立 Android 專案 MediaPlayer,套件 com.yiibai.mediaplayer,Target SDK 取最新。 |
| 2 | 修改 src/MainActivity.java。 |
| 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;
}
}
這裡有兩個值得學的技巧。第一,用 Handler 搭配 postDelayed 每 100 毫秒更新一次時間與 SeekBar,讓進度條看起來是平滑前進的。第二,快轉與倒退都先檢查是否超出範圍,超出就跳提示,避免呼叫 seekTo 之後出現位置錯亂。
<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 連上電腦後,開啟主要 Activity 並按下執行:
IDE 會詢問要執行在哪個目標裝置上。
選好裝置,畫面如下。此時暫停鍵為不可用狀態:
按下播放鍵,播放鍵變灰、暫停鍵啟用,時間與進度條開始走動:
按下暫停鍵,音樂停在當前位置並跳出提示:
再按播放鍵會從暫停處續播。此時試著按快轉或倒退,若已逼近曲子結尾而再往前跳會超出總長度,就會看到類似下面的提示:
最後補充一點實務經驗:這個範例在按 Home 離開後音樂仍會繼續播放,因為 MediaPlayer 的生命週期沒有與 Activity 綁定。正式產品要做背景播放,應該改用 Foreground Service 搭配通知列,並在 Activity 的 onPause 或 onStop 中決定是否暫停,同時在 onDestroy 呼叫 release() 釋放資源,否則容易在多次進入後出現記憶體與音訊資源的問題。
Android JSON 解析入門:從天氣 API 擷取資料
JSON 是應用程式之間常見的資料交換格式,因為結構清楚、易於閱讀,也方便在 Android 中處理。當 App 需要從網路取得資料時,通常會先取得 JSON 字串,再解
Android 多媒體播放:用 MediaPlayer 實作音樂播放器
Android 提供了多種方式來控制音訊與影片檔案及串流的播放,其中最主要的途徑就是名為 MediaPlayer 的類別。 MediaPlayer 這個類別讓你能存取 A
Chronometer 控件實現的 Android 計時器教學
本文示範使用 Chronometer 建立計時器,可設定秒數、開始、停止與重置,並在時間到時跳出提示。實作原理Chronometer 會從 setBase 設定的基準時間
Android 6.0 指紋識別開發實例:FingerprintManager 註冊流程
Android 6.0 之後,指紋識別可由 FingerprintManager 提供支援。本文以高通 64 位平台與 fpc1020 為例,說明如何撰寫指紋註冊畫面,並