編輯:Android 開發實例
Android 提供多種播放音訊與影片的方式,其中最直接的就是 MediaPlayer 類別。它是內建媒體播放服務的 facade,音訊、影片與串流都能透過它控制。
最常見的取得方式,是呼叫靜態方法 create():
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數指向音訊資源,所以必須先在專案裡建立名為 raw 的資料夾,把音樂檔放進去。
物件到手後,用兩個方法就能操控播放:
mediaPlayer.start(); mediaPlayer.pause();
行為上有個容易混淆的地方:start() 在初次呼叫時從頭播放,但在 pause() 之後再呼叫,會從暫停點續播。若要強制回到開頭,得先 reset():
mediaPlayer.reset();
除此之外,還有這些方法值得熟悉:
| 編號 | 方法 | 說明 |
|---|---|---|
| 1 | isPlaying() | 回傳布林值,指出目前是否正在播放。 |
| 2 | seekTo(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 | 用 Android Studio 建立專案 MediaPlayer,套件名 com.yiibai.mediaplayer,Target SDK 與編譯版本取最新 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.text iew4);
startTimeField = (TextView)findViewById(R.id.text iew1);
endTimeField = (TextView)findViewById(R.id.text iew2);
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;
}
}
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/text iew2" android:layout_toRightOf="@+id/text iew1" /> <TextView android:id="@+id/text iew1" 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/text iew2" 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/text iew3" 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/text iew3" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/text iew4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/text iew3" android:layout_alignBottom="@+id/text iew3" 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="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>
確認 Android 手機已連上電腦,開啟任一 Activity 檔並按下工具列的執行鈕:
IDE 會先跳出一個視窗,讓你決定要把 App 跑在哪裡:
選定裝置後,手機上會出現播放器的操作畫面:
此時暫停鈕是停用狀態。按下播放鈕,兩顆按鈕的啟用狀態會互換:
音樂持續播放中,按下暫停會看到提示訊息:
再按播放,曲子會從暫停處續播而非回到開頭。試著按快轉或倒轉,每次跳 5 秒;若已經頂到曲子的頭或尾而無法再跳,就會看到類似下面的提示:
最後提醒:切去做別的事時,音樂仍會在背景继续播放。要讓它停下來,得回到這個 App 結束播放,或從系統的執行中應用程式清單把它關掉。
Android JSON 解析常見錯誤排查:從 JSONObject 例外反推資料結構
JSON 是 JavaScript 對象符號的縮寫,如今已成為一門獨立的資料交換格式,也是 XML 最有力的替代方案。它比 XML 短、比 XML 好讀,解析時也不必處理
Android手機衛士(十七):用自訂屬性擴充設定項
前面已完成設定中心第一欄,接下來要讓其他設定欄也能重複使用。做法是為自訂 SettingItemView 宣告可配置屬性。宣告自訂屬性在 res/values/attrs
用 User Agent 正確分辨 Android 手機與平板的安全做法
隨著 Android 裝置數量暴增,愈來愈多網站需要針對它們做調整,而主流類型不外乎手機與平板。問題是:在適配時,該如何透過 User Agent(以下簡稱 UA)把兩者
Android 中的 SAX 解析:事件驅動的 XML 讀寫實作
Android 上處理 XML 有兩條路:DOM 與 SAX。DOM 會把整份文件讀進記憶體再操作,方便隨意跳轉查詢,但記憶體開銷大;SAX 則是事件驅動,解析器一邊讀一