編輯:Android 開發實例
要在 App 裡播放一段音樂,Android 給了你不少選擇,但最常被拿出來用的仍是 MediaPlayer。它把底層的播放服務包成一個好操作的物件,不論音樂是打包在 App 內、放在外部儲存空間,還是來自網路串流,都能用它處理。
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
靜態方法 create() 會回傳一個已準備好可播放的 MediaPlayer 實體。第二個參數是媒體資源,若要播放 App 內附的檔案,必須先在專案裡新增名為 raw 的資料夾,把音樂放進去。
mediaPlayer.start(); mediaPlayer.pause(); mediaPlayer.reset();
start() 開始播放;pause() 暫停,再次呼叫 start() 會從暫停處續播。若希望回到開頭,必須先呼叫 reset() 把播放器重設。
| 方法 | 說明 |
|---|---|
isPlaying() | 回傳是否正在播放。 |
seekTo(int position) | 跳到指定的播放位置(毫秒)。 |
getCurrentPosition() | 取得目前播放位置(毫秒)。 |
getDuration() | 取得媒體總長度(毫秒)。 |
reset() | 把播放器重設為初始狀態。 |
release() | 釋放播放器占用的資源。 |
setVolume(float left, float right) | 設定左右声道音量(0.0~1.0)。 |
setDataSource(FileDescriptor fd) | 指定播放的資料來源。 |
selectTrack(int index) | 選取指定索引的軌道。 |
getTrackInfo() | 回傳各軌道的資訊陣列。 |
這個範例會做出一個真正的播放器介面:歌曲名稱、目前時間/總長度、播放與暫停鈕、快轉與快退各 5 秒,以及一條隨播放同步移動的 SeekBar。因為要實際出聲,請用真機測試。
| 步驟 | 做法 |
|---|---|
| 1 | 建立 Android 專案 MediaPlayer,套件名 com.example.mediaplayer,Target SDK 與 Compile With 使用較新版本。 |
| 2 | 修改 src/MainActivity.java,加入 MediaPlayer 相關程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,加入所需的 XML 元件。 |
| 4 | 修改 res/values/string.xml,加入字串資源。 |
| 5 | 新增 raw 資料夾,放入 song.mp3。 |
| 6 | 執行 App,選擇已連線的裝置並驗證。 |
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;
}
}
<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/textV8iew2"
android:layout_toRightOf="@+id/textV8iew1" />
<TextView android:id="@+id/textV8iew1"
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/textV8iew2"
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/textV8iew3"
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/textV8iew4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textV8iew3"
android:layout_alignBottom="@+id/textV8iew3"
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="action_settings">Settings</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 跑在哪裡:
選好裝置後,畫面會呈現播放器的初始狀態:
此時暫停鈕是 disabled。按下播放鈕,兩顆按鈕的啟用狀態會互換:
音樂持續播放,按下暫停鈕會看到對應的提示:
再按播放,音樂會從暫停處續播。接著試著快轉或快退 5 秒;當快轉會超出總長度時,程式會以 Toast 告知無法跳轉:
這個播放器的音樂在你切去其他 App 時仍會在背景播放。要徹底停止,得離開這個應用程式。在真實專案中,請於 onDestroy() 呼叫 mediaPlayer.release(),並視需求在 onPause() 決定是否暫停播放;否則旋螢幕或離開頁面後,播放器占用的資源不會被回收,容易導致記憶體不足或聲音播放失控。
Android 設計模式之策略模式:以動畫 Interpolator 為例
策略模式其實特別簡單(看到這句話,是不是心裡一下放鬆了?)。 舉個例子:排序。官方定義一個排序接口 ISort,裡面有一個 sort() 方法;民間各自實現——冒泡、快速
用 Android Canvas 手繪南丁格爾玫瑰圖(Nightingale Rose Diagram)
第一次看到南丁格爾玫瑰圖時,我在常規圖表裡實在感到驚艷——但老實說,第一眼沒看懂。查了背景才知道這位女士有多麼了不起,確實值得尊敬。 仔細研究之後發現,這種圖的構成原理其
Android 多媒體播放:MediaPlayer 用法與完整播放器範例
要在 Android 上播放音訊或影片,可以走不同的技術路線,但最經典、也最常被拿來入門的是 MediaPlayer。它被封裝在 android.media 套件中,作為
從支付寶與微信首頁看 Android 事件分發:可拖曳 GridView 實戰
很多 Android 開發者會以支付寶、微信首頁作為事件分發的練習題,因為這類頁面常同時包含 ViewPager、ScrollView、GridView 與拖曳排序,很容