編輯:Android 開發實例
Android 提供了多種控制音訊/影片播放的方式,其中最常用的是 MediaPlayer 類別。
MediaPlayer 讓我們存取系統內建的媒體播放服務來播放音訊、影片。使用時只要呼叫靜態的 create() 方法即可取得實例:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是要播放的媒體資源,你必須先在專案下建立名為 raw 的資料夾並放入音樂檔。
取得物件後,就能呼叫方法控制播放,最常見的兩個是:
mediaPlayer.start(); mediaPlayer.pause();
呼叫 start() 會從頭播放;若先 pause() 再 start(),則從暫停處續播。若想從頭開始,需先呼叫 reset():
mediaPlayer.reset();
此外還有許多實用方法:
| 方法 | 說明 |
|---|---|
| isPlaying() | 回傳是否正在播放。 |
| seekTo(position) | 將播放位置跳到指定毫秒數。 |
| getCurrentPosition() | 取得目前播放位置(毫秒)。 |
| getDuration() | 取得媒體總長度(毫秒)。 |
| reset() | 重設播放器。 |
| release() | 釋放播放器資源。 |
| setVolume(left, right) | 設定左右声道音量。 |
| setDataSource(fd) | 指定媒體資料來源。 |
以下範例打造一個可播放、暫停、快轉與倒轉的音樂播放器。建議在真機上運行以聽到聲音。
操作步驟:
src/MainActivity.java。res/layout/activity_main.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 進階:用 BLE 開發搜索 iBeacon 基站
前文講述了 Android 手機與 BLE 終端之間的通信,而最常見的 BLE 終端,莫過於蘋果公司倡導的 iBeacon 基站。iBeacon 技術基於 BLE,其特點
Android 端如何解析 JSON?JSONObject 用法與天氣 App 完整實作
JSON 的全名是 JavaScript Object Notation,但今日它早已脫離 JavaScript 的框架,成為跨語言通用的資料交換格式,也是 XML 在
Android 本地化:讓同一支 App 在不同語言環境下說不同的話
一支上架的 App,可能同時被義大利米蘭的使用者、日本東京的使用者、德國柏林的用戶打開。若所有文字都寫死在程式碼裡,海外市場就等於放棄。Android 對這件事有非常漂亮
Android 登入畫面教學:帳密欄位設計與三次錯誤後鎖定的實作
登入畫面是使用者進入 Facebook、微博這類服務前的第一道門。它要收集一組憑證,驗證通過就放行。聽起來平凡,但實作時有三個細節決定成品是否堪用:密碼欄有沒有遮好、錯誤