編輯:Android 開發實例
要在 App 裡播放音訊或影片,最直接的方式是使用 Android 內建的 MediaPlayer 類別。它封裝了底層的播放服務,讓你不必煩惱解碼細節,專心處理播放控制。
取得 MediaPlayer 實例最常見的做法是呼叫靜態方法 create():
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是音訊資源 ID。使用前必須先在專案裡新增一個名為 raw 的資料夾,把音樂檔放進去,Android 便會自動為它產生資源 ID。
物件建立完成後,就能用 start() 與 pause() 控制播放:
mediaPlayer.start(); mediaPlayer.pause();
要留意兩者的行為差異:呼叫 start() 會從頭開始播;若中途 pause() 之後再 start(),則會從暫停的位置續播,而不是回到開頭。
如果你希望無論如何都從第一秒重新開始,就必須先呼叫 reset():
mediaPlayer.reset();
除了播放與暫停,這個類別還提供了不少實用方法:
| 編號 | 方法與說明 |
|---|---|
| 1 | isPlaying()回傳布林值,表示目前是否正在播放。 |
| 2 | seekTo(int position)把播放位置跳到指定的毫秒數。 |
| 3 | getCurrentPosition()取得目前的播放位置,單位為毫秒。 |
| 4 | getDuration()取得整首曲子的總長度,單位為毫秒。 |
| 5 | reset()把播放器重設為初始狀態。 |
| 6 | release()釋放播放器持有的所有資源,非用不可省。 |
| 7 | setVolume(float left, float right)分別設定左右聲道的音量。 |
| 8 | setDataSource(FileDescriptor fd)指定音訊或影片的資料來源。 |
| 9 | selectTrack(int index)依索引選取特定軌道。 |
| 10 | getTrackInfo()回傳軌道資訊陣列。 |
以下範例做出一個能播放、暫停、快轉與倒轉五秒的播放器,並用 SeekBar 即時顯示播放進度。由於要實際聽到聲音,建議在真機上測試。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Eclipse(或 Android Studio)建立專案,命名為 MediaPlayer,套件名稱 com.yiibai.mediaplayer,Target SDK 與 Compile With 請對齊最新版 SDK。 |
| 2 | 修改 src/MainActivity.java 加入 MediaPlayer 相關程式碼。 |
| 3 | 修改 res/layout/activity_main.xml 加入對應元件。 |
| 4 | 修改 res/values/string.xml 加入字串資源。 |
| 5 | 在專案下新增名為 raw 的資料夾,放入 song.mp3。 |
| 6 | 執行 App,安裝到裝置並驗證結果。 |
src/com.yiibai.mediaplayer/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.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 毫秒更新一次進度條,以及用 oneTimeOnly 旗標確保 SeekBar 的最大值只設定一次。
res/layout/activity_main.xml:
<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>
res/values/string.xml:
<?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>
AndroidManifest.xml:
<?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>
假定你已把手機連上電腦,開啟任一 Activity 檔後點擊工具列上的執行鈕:
Eclipse 會先跳出一個視窗,讓你選擇要把 App 跑在哪裡:
選好自己的手機,畫面上會出現播放器的初始狀態:
此時暫停鈕是灰的。按下播放鈕後,兩顆按鈕的啟用狀態會互換:
音樂正在進行中,按下暫停鈕會看到對應的提示訊息:
再次按下播放鈕,曲子會從剛剛暫停的位置接著播,而不是回到開頭。快轉與倒轉鈕則以五秒為單位跳躍;當已經逼近曲子末端、無法再往前跳時,程式會跳出提示:
最後要提醒的是,這個範例的音樂會在你切到其他工作時繼續於背景播放。想讓它停下來,必須從背景工作列表中把 App 結束掉——實務上更理想的做法,是在 onPause() 或 onStop() 中呼叫 release(),妥善釋放播放器資源。
Android Toast 提示訊息使用教學
Toast 是 Android 中最常見的輕量提示方式。它會短暫顯示訊息,然後自動消失,不需要使用者點擊確認,也不會中斷目前 Activity 的操作。Toast 的使用
Android ViewPager 多頁滑動與頁卡動畫實作
本文以類似行動社群應用的頁卡體驗為例,示範如何運用 ViewPager 完成多頁面的手勢切換,並讓頂部頁卡下方的白色橫條在切換時平滑移動。先認識 ViewPagerVie
手把手做 Android 登入頁:表單、驗證與錯誤嘗試的處理
登入畫面是許多 App 的第一道門。使用者要嘛成功進入,要嘛被擋在門外——而這中間的體驗細節,往往決定了對這個 App 的第一印象。本文從版面配置寫到程式邏輯,做出一個具
Android TextView 控件詳解:屬性、方法與使用要點
文本控件的兩大主力 在 Android 開發中,凡是需要與「文字」打交道的地方,都離不開兩個控件:TextView 與 EditText。前者負責展示,後者負責收集輸入。