編輯:Android 開發實例
MediaPlayer 只負責「播放」這件事,它不會告訴使用者現在播到哪裡。要讓介面呈現流暢的播放進度,得自己定時去問它目前的位置,再把結果畫到 SeekBar 上。這就是本章範例的核心:一個用 Handler 定時輪詢、能前進後退五秒的完整播放器。
先用靜態 create() 建立播放器,音樂檔放在 res/raw:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
播放與暫停:
mediaPlayer.start(); mediaPlayer.pause();
start() 首次呼叫從頭播起;從 pause() 恢復時則接著上次的位置。若要強制回到開頭,先呼叫 reset():
mediaPlayer.reset();
| 方法 | 說明 |
|---|---|
| isPlaying() | 是否正在播放。 |
| seekTo(int position) | 跳到指定毫秒位置。 |
| getCurrentPosition() | 目前播放位置(毫秒)。 |
| getDuration() | 總長度(毫秒)。 |
| reset() | 重設播放器。 |
| release() | 釋放資源。 |
| setVolume(float, float) | 設定左右声道音量。 |
| setDataSource(FileDescriptor) | 指定資料來源。 |
| selectTrack(int index) | 選取軌道。 |
| getTrackInfo() | 取得軌道資訊陣列。 |
| 步驟 | 要做的事 |
|---|---|
| 1 | 用 Android Studio 建立 MediaPlayer 專案,套件名 com.yiibai.mediaplayer。 |
| 2 | 修改 MainActivity.java 加入播放控制與 Handler 輪詢。 |
| 3 | 修改 activity_main.xml 加入四顆 ImageButton 與 SeekBar。 |
| 4 | 修改 res/values/string.xml。 |
| 5 | 新增 res/raw 資料夾並放入 song.mp3。 |
| 6 | 用真機執行,確認有聲音輸出。 |
MainActivity.java:
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.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.textV4); startTimeField = (TextView)findViewById(R.id.textV1); endTimeField = (TextView)findViewById(R.id.textV2); 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_alignParentBottom="true" android:onClick="forward" android:src="@android:drawable/ic_media_ff" /> <ImageButton android:id="@+id/imageButton1" android:layout_toRightOf="@id/imageButton3" android:onClick="play" android:src="@android:drawable/ic_media_play" /> <ImageButton android:id="@+id/imageButton2" android:layout_toRightOf="@id/imageButton1" android:onClick="pause" android:src="@android:drawable/ic_media_pause" /> <ImageButton android:id="@+id/imageButton4" android:layout_toRightOf="@id/imageButton2" android:onClick="rewind" android:src="@android:drawable/ic_media_rew" /> <SeekBar android:id="@+id/seekBar1" android:layout_above="@id/imageButton3" /> <TextView android:id="@+id/textV1" android:text="@string/inital_Time" android:layout_alignTop="@id/seekBar1" /> <TextView android:id="@+id/textV2" android:text="@string/inital_Time" android:layout_alignTop="@id/seekBar1" android:layout_alignParentRight="true" /> <TextView android:id="@+id/textV3" android:text="@string/hello_world" /> <TextView android:id="@+id/textV4" android:layout_alignBaseline="@id/textV3" android:layout_toRightOf="@id/imageButton1" /> </RelativeLayout>
string.xml 與 manifest:
<resources> <string name="app_name">MediaPlayer</string> <string name="hello_world">Now Playing:</string> <string name="inital_Time">0 min, 0 sec</string> </resources> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.mediaplayer"> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
接上真機後按下執行
鈕,先選擇要安裝的裝置:
App 啟動後顯示播放器主畫面,此時暫停鈕不可用:
按下播放,播放鈕變灰、暫停鈕亮起,SeekBar 開始往右走:
按下暫停,跳出一個提示訊息,音樂停在原地:
再按播放會從暫停處續播。若一路快轉到接近尾聲,就會看到「無法再往前跳 5 秒」的提示:
實作上有兩點值得留意:Handler 的輪詢間隔若設得太短會讓 UI 一直被 redraw,100 毫秒是相當常見的折衷;另外 Activity 銷毀時記得取消 postDelayed 並呼叫 release(),否則 Runnable 會繼續持有已失效的頁面參考,造成記憶體洩漏。
Android 9-patch圖片製作全流程(圖文並茂)
做 Android 開發,最讓人頭疼的莫過於沒有稱心的美工素材,一拉伸界面就失真,整體觀感大打折扣。有的時候我們會在 drawable-hdpi、mdpi、ldpi 各個
Android JSON 解析教學:以天氣 API 為例的實務流程
JSON 是目前 Android 應用常遇到的資料格式。當伺服器回傳 JSON 字串時,開發者需要把文字轉成物件,再取出所需欄位。本文以天氣資料為例,說明解析流程。 常見
Android 應用本地化:讓同一個 App 說各國語言
一個上架 Google Play 的 App,可能在幾十個國家的裝置上被開啟。使用者對「文字、數字、日期、檔案」的期待各不相同,如果 App 永遠只顯示一種語言,體驗與留
Android 進階:SurfaceView 與多線程混搭實例
前文簡單介紹了 Android 中 SurfaceView 的基本用法,本文則進一步探討 SurfaceView 與多線程的混搭。之所以要將兩者結合,是為了避免動畫閃爍—