編輯:Android 開發實例
Android 提供多種控制音訊與影片播放的方式,其中最常被直接使用的一條路徑,是名為 MediaPlayer 的類別。它讓你能播放音訊、影片與串流內容,而不必自行處理編碼解碼的細節。
要使用 MediaPlayer,最簡便的方式是呼叫這個類別的靜態 create() 方法,它會回傳一個 MediaPlayer 實例:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是要播放的歌曲。如果檔案要隨 App 一起打包,必須在專案底下新增一個名為 raw 的資料夾,把音樂檔放進去。
物件建立好之後,就能呼叫方法控制播放:
mediaPlayer.start(); mediaPlayer.pause();
呼叫 start() 時音樂從頭開始播放。若在 pause() 之後再次呼叫 start(),則會從被停住的位置續播,而不是回到開頭。
若一定要從頭開始,必須先呼叫 reset():
mediaPlayer.reset();
| 方法 | 說明 |
|---|---|
isPlaying() | 回傳 true/false,表示目前是否正在播放。 |
seekTo(position) | 接受整數參數,將播放位置移到指定的毫秒數。 |
getCurrentPosition() | 回傳目前播放位置(毫秒)。 |
getDuration() | 回傳整首歌的總長度(毫秒)。 |
reset() | 重設媒體播放器。 |
release() | 釋放 MediaPlayer 物件所占用的資源。 |
setVolume(leftVolume, rightVolume) | 設定播放器的左右声道音量。 |
setDataSource(FileDescriptor fd) | 設定音訊或影片的資料來源。 |
selectTrack(int index) | 依整數索引選取清單中的特定軌道。 |
getTrackInfo() | 回傳軌道資訊的陣列。 |
這個範例示範如何使用 MediaPlayer,做出一個能播放、暫停、前進與後退歌曲的基本播放器。由於需要實際聽到聲音,建議在真機上執行。
| 步驟 | 做法 |
|---|---|
| 1 | 使用 IDE 建立 Android 應用,命名為 MediaPlayer,套件 com.yiibai.mediaplayer;Target SDK 與 Compile With 請設為最新版本的 Android SDK 以便使用較高階 API。 |
| 2 | 修改 src/MainActivity.java 加入 MediaPlayer 程式碼。 |
| 3 | 修改 res/layout/activity_main.xml 加入對應的 XML 元件。 |
| 4 | 修改 res/values/string.xml 加入必要字串。 |
| 5 | 在 MediaPlayer 專案下新增名為 raw 的資料夾,放入名為 song.mp3 的音樂檔。 |
| 6 | 執行應用,選擇執行中的 Android 裝置安裝並驗證結果。 |
主活動 src/com.yiibai.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.textViedw4);
startTimeField = (TextView)findViewById(R.id.textViedw1);
endTimeField = (TextView)findViewById(R.id.textViedw2);
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_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_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_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" />
<TextView android:id="@+id/textViedw1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/inital_Time" />
<TextView android:id="@+id/textViedw2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/inital_Time" />
<TextView android:id="@+id/textViedw3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/hello_world" />
<TextView android:id="@+id/textViedw4" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="TextView" />
</RelativeLayout>
字串資源 res/values/string.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MediaPlayer</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" >
<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 會顯示一個視窗讓你選擇執行位置:
選擇你的行動裝置作為執行目標,裝置上便會顯示預設畫面:
預設狀態下暫停鈕是停用的。按下播放鈕後,播放鈕轉為停用、暫停鈕轉為啟用:
至此音樂正在播放。按下暫停鈕會看到暫停提示:
再按一次播放鈕,歌曲不會從頭開始,而是從暫停處續播。接著可測試快轉或倒轉鈕,每次跳過五秒。當歌曲已接近尾端、無法再往前跳時,會出現類似以下的提示:
還有一點值得注意:當你在手機上執行其他工作時,音樂仍會在背景持續播放。若要讓它停下來,必須從背景活動清單中結束這個應用。
Android 自動亮度調節全流程拆解:從 Settings 到 PowerManager
手機能隨著環境光線自動調亮或調暗螢幕,靠的是 LIGHT 光線感應器。這條鏈路從設定界面一路延伸到系統服務,中間繞了不少彎,下面把整個流程理一遍。 一、從設定界面入手
深入淺析 Android Fragment(下篇):回退堆疊、通訊與旋轉重建
上篇談了 Fragment 的由來、生命週期、靜態與動態使用,以及 FragmentTransaction 的常用方法。這篇接著處理更實際的問題:回退堆疊怎麼管、Frag
MediaPlayer 音訊與視訊播放:搭配 SurfaceView 與 SeekBar 的完整實作
前面的文章把 Android 介面的入門技術介紹得差不多了,相信讀者對常見的 Layout 與 View 都已經有概念。接下來不再談介面,改針對具體功能逐一深入。 本文
Android 自定義 Animation 實現 3D 翻頁旋轉效果
Android 的動畫體系裡,補間動畫(tweened animation)之外的另一條路是自定義 Animation——直接接管 Matrix 變換。本文通過繼承 An