編輯:Android 開發實例
Android 想播放一段音訊或影片,最直接的入口就是 MediaPlayer。它站在系統的媒體播放服務之上,把解碼、音訊輸出這些底層細節都收 ourselves 起來,開發者只要告訴它「播這個來源」、「現在暫停」、「跳到第 30 秒」,它就會照辦。
最省事的方式是靜態方法 create(),它會一次完成建立與準備,直接回傳可用的物件:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是資源 id。使用前必須在專案裡新增名為 raw 的資料夾,把音樂檔放進去,Android 便會自動產生對應的 R.raw.song。
mediaPlayer.start(); mediaPlayer.pause();
這裡有個容易搞混的地方:第一次呼叫 start() 會從頭播起,但在 pause() 之後再呼叫 start(),是從暫停的位置續播。想真正回到開頭,得先 reset():
mediaPlayer.reset();
| 方法 | 說明 |
|---|---|
isPlaying() | 回傳是否正在播放。 |
seekTo(int ms) | 跳到指定毫秒位置,快轉快退的核心。 |
getCurrentPosition() | 目前播放位置(毫秒)。 |
getDuration() | 總時長(毫秒)。 |
reset() | 重設播放器狀態。 |
release() | 釋放所有持有的資源。 |
setVolume(float, float) | 設定左右聲道音量(0.0~1.0)。 |
setLooping(boolean) | 是否循環播放。 |
prepareAsync() | 非同步準備,網路來源時必用。 |
由於要實際聽到聲音,建議把 App 跑在真機上。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案 MediaPlayer(套件 com.yiibai.mediaplayer),Target SDK 與 Compile With 選最新版本。 |
| 2 | 修改 src/MainActivity.java,加入播放控制程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,放入四顆 ImageButton 與 SeekBar。 |
| 4 | 修改 res/values/strings.xml,補上顯示文字。 |
| 5 | 新增 raw 資料夾,放入 song.mp3。 |
| 6 | 執行並在裝置上驗證。 |
MainActivity.java:
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();
}
}
}
activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton android:id="@+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
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_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_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_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/textValue2"
android:layout_toRightOf="@+id/textValue1" />
<TextView android:id="@+id/textValue1"
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" />
<TextView android:id="@+id/textValue2"
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" />
<TextView android:id="@+id/textValue3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imageButton3"
android:text="@string/hello_world" />
<TextView android:id="@+id/textValue4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textValue3"
android:layout_alignBottom="@+id/textValue3"
android:layout_toRightOf="@+id/imageButton1"
android:text="TextView" />
</RelativeLayout>
strings.xml:
<resources>
<string name="app_name">MediaPlayer</string>
<string name="hello_world">Now Playing:</string>
<string name="inital_Time">0 min, 0 sec</string>
</resources>
把真機接上電腦,開啟專案的 Activity 檔後按下工具列的執行鈕:
IDE 會先跳出視窗,讓你選擇要把 App 跑在哪裡:
選好裝置後,手機上會出現播放器的初始畫面:
此時暫停鈕是 disabled 的灰色狀態。按下播放鈕後,兩顆按鈕的可用狀態對調,時間與進度條開始推進:
按下暫停鈕,畫面會跳出暫停的提示:
再按播放,音樂從暫停處續播而非回到開頭。按快轉或快退可前後跳 5 秒;當快轉已達曲尾時再按,就會看到提示訊息:
切換到其他 App 時,音樂仍會在背景持續播放,要讓它停下就得回到這個 App 並結束它。
product ion 等級還要補三件事:第一,範例用 Handler.postDelayed() 每 100 毫秒更新進度,離開時必須 myHandler.removeCallbacks(UpdateSongTime),並在 onDestroy() 呼叫 mediaPlayer.release(),否則音訊資源不會被回收。第二,若要支援鎖定螢幕控制與通知列播放,需改用 MediaSession 搭配前景服務。第三,範例只處理了本機 raw 資源;若播放網路串流,記得改用 setDataSource(url) 加 prepareAsync() 與 OnPreparedListener,並在 AndroidManifest.xml 補上 INTERNET 權限。
Android JSON 解析實務:抓取天氣 API 的關鍵欄位
在 Android 中,JSON 是常見的資料格式。要解析天氣 API 回傳的資料,可以先建立 JSONObject,再逐層取出 sys、main 等區塊。 觀察 JSO
Android自定義Dialog實戰詳解:帶WebView與多按鈕的彈窗
工作一個多月了,對 Android 的很多東西都有了新的認識,或者說才真正掌握。為了讓更多像我當初那樣的新手少走彎路,我會堅持把工作中遇到的、印象深刻的知識點整理出來分享
Android ListView 常見用法實戰:從默認布局到多選與點擊響應
ListView 是列表展示的首選控件(在 RecyclerView 普及之前更是如此)。本文用一套由淺入深的示例,把它的三要素、默認布局、多選模式與事件響應串起來講。
Android 遊戲開發實踐:角色移動時的地圖平滑滾動處理
先看效果: 地圖滾動的原理 此前寫過角色在屏幕內移動的方式,但那時拼出來的地圖正好鋪滿整個屏幕,因此不必操心滾動問題。當地圖大於屏幕時,事情就複雜了:既要讓角色看起來