編輯:Android 開發實例
Android 提供多種播放音訊與影片的方式,其中最通用的就是 MediaPlayer 類別。它被封裝在系統的媒體播放服務之上,讓你能用幾行程式碼就完成播放控制。
取得播放器實體的標準做法是呼叫靜態的 create():
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是音檔資源。使用這種寫法時,記得先在專案裡建立名為 raw 的資料夾,把音樂檔放進去。
物件建立好之後,最基本兩個動作是啟動與暫停:
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(leftVolume, rightVolume) | 設定左右声道音量。 |
| 8 | setDataSource(FileDescriptor fd) | 指定資料來源。 |
| 9 | selectTrack(int index) | 選取指定索引的軌道。 |
| 10 | getTrackInfo() | 回傳軌道資訊陣列。 |
以下範例會做出播放/暫停切換、前後跳 5 秒、進度條即時同步,並用 Toast 提示操作結果的播放器介面。因為要實際出聲,建議用真機測試。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Eclipse 建立 Android 專案,套件名 com.yiibai.mediaplayer,Target SDK 與 Compile With 選最新版本。 |
| 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.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/textView2"
android:layout_toRightOf="@+id/textV 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/textV 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>
<?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>
假設手機已透過 USB 連上電腦。在 Eclipse 中開啟 Activity 檔,點擊工具列的執行圖示:
Eclipse 接著會詢問要執行在哪個目標上:
選擇你的行動裝置,手機上就會出現播放畫面:
預設狀態下暫停鈕是停用(灰色)的。按下播放鈕後兩者狀態互換:
音樂正在播放,按下暫停會看到提示訊息:
再次按下播放,曲子從剛才暫停的位置接著播。此時按快轉或倒轉可前後跳 5 秒;若已快轉到尾端,就會看到「無法再往前跳」的提示:
另外別忘了:切換到其他工作時音樂仍在背景播放,要停止必須回到這個應用並結束它。
Android 面試常考:gravity 與 layout_gravity 到底差在哪
這兩個屬性名字只差一個前綴,作用卻完全不同,是初學者最容易混淆的一組: android:gravity:決定控制項內部內容的對齊方式。例如按鈕裡那行文字要貼左、居中還是
在 Eclipse 中導入 Android SDK Sample 專案的正確方式
Android SDK 內附的 Sample 範例是學習 Android 的重要資源。然而,若直接用一般 Import 方式,可能會把原始範例複製到工作區,或造成原目錄被
Android 多媒體播放:MediaPlayer 基本用法
播放音訊前的準備若要在 Android 中播放音訊,可將檔案放在 raw 資源資料夾,或使用 MediaPlayer 指定資料來源。最簡單的方式是使用 create 方法
Android 手機衛士(十):首頁佈局與淡入動畫
啟動頁淡入動畫從 splash 進入 home 時,可以加入淡入動畫,讓畫面切換更柔和。做法是在 onCreate 中呼叫 initAnimation,建立 AlphaA