編輯:Android 開發實例
要在 Android 上播放音訊或影片,最直接的方式就是使用 MediaPlayer 類別。它是內建媒體播放服務的入口,音訊、影片與串流格式都能 handle。
取得 MediaPlayer 實例最常見的做法是呼叫靜態方法 create():
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是音訊資源。使用前必須先在專案裡新增一個名為 raw 的資料夾,並把音樂檔放進去。
物件建立好之後,用 start() 與 pause() 就能控制播放:
mediaPlayer.start(); mediaPlayer.pause();
這裡有個容易踩到的細節:呼叫 start() 會從頭開始播;若在 pause() 之後再次呼叫 start(),則會從暫停的位置續播。若想強制回到開頭,必須先呼叫 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() | 回傳軌道資訊陣列。 |
這個範例做出一個能播放、暫停、快轉與倒轉的簡易播放器。由於要真的聽到聲音,建議在實體裝置上測試。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 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 | 執行 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;
}
}
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="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 會跳出視窗,讓你選擇要執行在哪個目標上:
選好裝置後,畫面上會出現播放器的操作介面:
初始狀態下暫停鈕是灰的。按下播放鈕後,播放鈕變灰、暫停鈕轉為可用:
音樂播放中按下暫停,會看到提示訊息:
再次按下播放,音樂會從剛才暫停的位置續播,而不是跳回開頭。此時可以試著按快轉或倒轉,每次跳 5 秒;若已達結尾或開頭而無法再跳,就會看到對應的提示:
最後要提醒的是,切到其他工作時音樂仍會在背景持續播放。想讓它停下來,得回到這個 App 結束播放,或是在系統的執行中應用程式清單裡把它移除。
Android MediaPlayer(多媒體播放):音訊與影片控制入門
Android 提供了許多方法來控制播放的音訊/影片檔案與串流,其中主要的一種是透過名為 MediaPlayer 的類別。 MediaPlayer 類別讓 Android
Android 登入畫面實作:從輸入欄位到錯誤次數鎖定
這個題目要解決什麼 只要 App 需要帳號,就一定會有一塊登入介面:使用者輸入帳號與密碼,按下按鈕,由程式決定放行或退回。Facebook、微博這類服務是這樣,自家開發的
Android 廣播、服務、數據庫、通知、包等核心術語圖解
簡介Android 中運用了大量機制,例如廣播、服務、數據庫、通知、包等等。本文用圖文並茂的方式,對這些核心概念做一個直觀的梳理。什麼是廣播?Broadcast 是一種在
Android 登入畫面設計:帳密輸入與嘗試次數限制
設計登入畫面時,除了視覺配置,也要考慮互動流程。使用者輸入帳密後,系統應立即給予明確回饋。 密碼輸入 密碼欄位需要遮蔽輸入內容,避免旁人窺見。Android 可透過輸入型