編輯:Android 開發實例
要在 App 裡播放音訊或影片,Android 提供了多種途徑,其中最直接的就是 MediaPlayer。它屬於系統內建的媒體播放服務,透過這個類別,你能以幾行程式碼完成播放、暫停、跳轉等動作。
建立實例最常見的方式是呼叫靜態方法 create():
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數代表音訊資源。請先在專案下建立名為 raw 的資料夾,把音樂檔放進去,系統便會為它產生可參照的資源 ID。
物件到手後,用這兩個方法就能控制播放:
mediaPlayer.start(); mediaPlayer.pause();
行為差異值得記牢:呼叫 start() 會從頭播放;若在 pause() 之後再次呼叫,則從暫停處續播。想強制回到起點,得先呼叫 reset():
mediaPlayer.reset();
此外還有一批實用方法:
| 編號 | 方法與說明 |
|---|---|
| 1 | isPlaying() 回傳是否正在播放。 |
| 2 | seekTo(int position) 跳到指定的毫秒位置。 |
| 3 | getCurrentPosition() 取得目前播放位置(毫秒)。 |
| 4 | getDuration() 取得總時長(毫秒)。 |
| 5 | reset() 重設播放器。 |
| 6 | release() 釋放播放器持有的資源。 |
| 7 | setVolume(float leftVolume, float rightVolume) 設定左右声道音量。 |
| 8 | setDataSource(FileDescriptor fd) 設定媒體資料來源。 |
| 9 | selectTrack(int index) 依索引選取軌道。 |
| 10 | getTrackInfo() 回傳軌道資訊陣列。 |
以下範例做出一個能播放、暫停、快轉與倒轉的播放器,並以 SeekBar 呈現即時進度。由於必須實際出聲,請使用真機測試。
| 步驟 | 做法 |
|---|---|
| 1 | 以 Eclipse 建立專案 MediaPlayer,套件 com.yiibai.mediaplayer,Target SDK 與編譯版本取最新。 |
| 2 | 於 src/MainActivity.java 加入 MediaPlayer 程式碼。 |
| 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.textViem4); startTimeField =(TextView)findViewById(R.id.textViem1); endTimeField =(TextView)findViewById(R.id.textViem2); 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; } }
版面:
<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/textViem2" android:layout_toRightOf="@+id/textViem1" /> <TextView android:id="@+id/textViem1" 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/textViem2" 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/textViem3" 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/textViem3" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textViem4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textViem3" android:layout_alignBottom="@+id/textViem3" 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="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>
假定已用手機連上電腦,開啟任一 Activity 檔後按下工具列的執行鈕:
IDE 接著會顯示選擇畫面,讓你決定在哪裡執行:
選定行動裝置後,手機上會出現播放器的初始畫面:
此時暫停鈕為停用狀態;按下播放鈕,兩者的啟用狀態對調:
音樂持續播放,按下暫停鈕會看到對應提示:
再按播放,曲子會從暫停處接續而非回到開頭。快轉與倒轉每次跳五秒,當已無法再往前跳時,程式會顯示類似下圖的提示:
要留意的是,這個範例的音樂會在你操作手機其他功能時持續於背景播放,想停掉必須從背景工作清單結束 App。若要做得更完善,可在 onPause() 判斷是否暫停、於 onDestroy() 呼叫 release(),並搭配前景服務與 MediaSession 提供通知列控制,讓使用者不必回到 App 也能操作播放。
Android 登錄實例:建立登入介面並管理錯誤嘗試
登入應用程式的畫面會要求使用者輸入憑證,才能登入某個特定的應用,例如 Facebook、微博等服務。 本章介紹如何建立一個登入介面,以及如何管理安全問題與錯誤嘗試次數。
Android GridView 多選效果的實作教學
相簿、多附件挑選這類介面常需要「點一下就能勾選多張圖」的 GridView。Android 的 GridView 本身沒有內建的多選視覺回饋,因此實作方式是自行維護一份「
Android ApiDemo 系列三:Activity 切換動畫
ApiDemo 的 Animation 範例示範在切換 Activity 時加入動畫效果。常見的兩種效果是淡入與縮放:淡入讓新畫面由透明逐漸顯示,縮放則讓新畫面由小變大出
Android 進階:SurfaceView 與多線程混搭實例
前文簡單介紹了 Android 中 SurfaceView 的基本用法,本文則進一步探討 SurfaceView 與多線程的混搭。之所以要將兩者結合,是為了避免動畫閃爍—