編輯:Android 開發實例
Android 提供了多種方式來控制音訊與影片檔案及串流的播放,其中最常用的一條路徑就是透過 MediaPlayer 這個類別。
MediaPlayer 是內建媒體播放器服務的一層存取介面,讓 App 能播放音訊、影片等內容。使用時,只要呼叫這個類別的靜態 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():回傳 true/false,表示是否正在播放。seekTo(position):跳至指定的秒數位置。getCurrentPosition():回傳目前播放位置,單位毫秒。getDuration():回傳整段媒體的總時長,單位毫秒。reset():重設媒體播放器。release():釋放 MediaPlayer 物件持有的所有資源。setVolume(float leftVolume, float rightVolume):設定播放器左右声道音量。setDataSource(FileDescriptor fd):設定音訊或影片的資料來源。selectTrack(int index):依索引選取列表中的特定軌道。getTrackInfo():回傳軌道資訊陣列。以下範例示範如何使用 MediaPlayer 類別,做出一個能播放、暫停、快轉與倒轉的簡易播放器。
操作步驟:
src/MainActivity.java,加入 MediaPlayer 程式碼。res/layout/activity_main.xml,加入對應的 XML 元件。res/values/string.xml,加入必要字串。raw 的資料夾,放入名為 song.mp3 的音樂檔。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.textViem4);
startTimeField = (TextView)findViewById(R.id.textViem1);
endTimeField = (TextView)findViewById(R.id.textViem2);
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/textViem2"
android:layout_toRightOf="@+id/textView1" />
<TextView android:id="@+id/textViem1"
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/textViem4"
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>
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>
接下來嘗試執行 MediaPlayer 應用。假設已將實體 Android 手機連上電腦,在 Eclipse 中開啟專案的 Activity 檔並點擊工具列的執行
圖示。開始執行前,Eclipse 會顯示視窗讓你選擇執行目標。
選擇你的行動裝置,接著檢查手機,它會顯示預設畫面:
預設會看到暫停鈕為停用狀態。按下播放鈕後,播放鈕變為停用、暫停鈕轉為啟用,如下圖:
此時音樂已經在播放。按下暫停鈕並觀察暫停提示,結果如下:
再按播放鈕時,歌曲不會從頭開始,而是從剛才暫停的位置續播。接著按快轉或倒轉鈕可前後跳 5 秒;當歌曲已無法再往前跳時,會出現類似以下的提示:
當你在手機上做其他事情時,音樂仍會持續在背景播放。若要停止,必須退出這個應用程式的背景活動,或在程式碼中確實呼叫 pause() 與 release() 釋放資源。
一個 App 打包多個廣告平台版本的完整方案
Android 的廣告平台多如牛毛,而各大應用地區分市場對平台的接受度並不一致。開發者要接入廣告,通常繞不開兩個問題: 接哪個平台更賺錢? 接哪個平台不會被市場拒絕?
Android 多語系支援:從 values-it 談字串本地化
一支上架的應用程式,使用者可能來自任何國家。要讓不同語言環境的人都讀得懂,就必須把介面文字、數字格式、日期寫法都調整成當地的習慣,這項工作稱為本地化。 Android 的
Android BroadcastReceiver 使用解析
BroadcastReceiver 是 Android 四大元件之一,用於接收系統或應用送出的廣播 Intent。它常用於監聽網路變化、電量、時區、語言切換等事件。 基本
Android MediaPlayer:打造可播放、暫停與快轉的音樂播放器
Android 提供了多種控制音訊/影片播放的方式,其中最常用的是 MediaPlayer 類別。 MediaPlayer 讓我們存取系統內建的媒體播放服務來播放音訊、