編輯:Android 開發實例
Android 提供了多種控制音訊/影片檔案與串流播放的方式,其中最常用、最直接的就是 MediaPlayer 這個類別。
MediaPlayer 讓我們得以存取系統內建的媒體播放服務,用來播放音樂、影片等內容。要使用它,只要呼叫該類別的靜態 create() 方法,就會取得一個 MediaPlayer 實例,語法如下:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數代表要播放的媒體資源。你必須先在專案底下建立一個名為 raw 的資料夾,再把音樂檔案放進去。
取得 MediaPlayer 物件後,就能呼叫相關方法來開始或停止播放,最常見的兩個如下:
mediaPlayer.start(); mediaPlayer.pause();
呼叫 start() 時音樂會從頭開始播放;若先呼叫 pause() 之後再次 start(),則會從暫停的位置續播,而非回到開頭。若真的想從頭開始,就必須先呼叫 reset():
mediaPlayer.reset();
除了 start() 與 pause(),這個類別還提供了許多實用的方法,能更細緻地處理音訊與影片:
| 方法 | 說明 |
|---|---|
| isPlaying() | 回傳布林值,表示目前是否正在播放。 |
| seekTo(position) | 將播放位置跳轉到指定的毫秒數。 |
| getCurrentPosition() | 取得目前播放位置(毫秒)。 |
| getDuration() | 取得整段媒體的總長度(毫秒)。 |
| reset() | 將播放器重設為初始狀態。 |
| release() | 釋放 MediaPlayer 物件所占用的資源。 |
| setVolume(left, right) | 設定左右聲道的音量。 |
| setDataSource(fd) | 指定音訊/影片的資料來源。 |
以下範例展示如何使用 MediaPlayer 打造一個具備播放、暫停、快轉與倒轉功能的音樂播放器。由於要實際聽到聲音,建議在真機上運行測試。
操作步驟:
src/MainActivity.java,加入 MediaPlayer 相關程式碼。res/layout/activity_main.xml,加入對應的 XML 元件。res/values/string.xml,加入必要字串。raw 的資料夾,放入名為 song.mp3 的音樂檔。主活動文件 src/com.example.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="action_settings">Settings</string> <string name="hello_world">Now Playing:</string> <string name="inital_Time">0 min, 0 sec</string> </resources>
在 Eclipse 中點擊工具列上的執行鈕
,選擇要運行的裝置:
選擇你的行動裝置後,畫面如下:
預設暫停鈕是停用狀態。按下播放鈕後,播放鈕會停用、暫停鈕則被啟用:
此時音樂正在播放,按下暫停鈕會看到暫停提示:
再次按下播放鈕,音樂會從暫停處續播而非回到開頭。此時可按快轉或倒轉鈕前後跳轉 5 秒;當無法再往前跳時會出現提示:
即使你切到其他工作,音樂仍會在背景持續播放;若要停止,必須從背景活動中結束這個應用。
Android 多語言應用:本地化字串與 values-it 資料夾怎麼用
一支上架的 App,很可能同時被台灣、日本、德國的使用者打開。要讓每個人都看得懂,App 就得依裝置的語言環境,換上對應的文字、數字與格式。這件事在 Android 裡稱
Android 應用本地化:讓 App 輕鬆支援多語言與地區
Android 應用往往運行在name不同國家、不同語言環境的裝置上。若希望 App 真正做到「在地化」,就必須讓文字、數字、日期與檔案等资源都能依裝置的語言環境自動切換
Android MediaPlayer 教學:做一個能播放、暫停與快轉的音樂播放器
Android 想播放音訊或影片,最直接的工具就是 MediaPlayer 這個類別。它被封裝在系統的媒體播放服務之上,能處理本機檔案、資源目錄中的素材,也能拉串流。
Android XML 靜態資源與 R.java 使用指南
Android 開發中,XML 靜態資源與 Java 程式碼經常搭配使用。XML 負責描述版面與資源,Java 負責控制邏輯,而 R.java 則是兩者之間的橋梁。R.j