編輯:Android 開發實例
Android 提供了多種控制音訊/影片檔案與串流播放的方式,其中最具代表性的是 MediaPlayer 類別。
透過 MediaPlayer,App 得以使用系統內建的媒體播放服務,播放音訊、影片等內容。要使用它,需呼叫該類別的靜態 create() 方法,此方法會回傳一個 MediaPlayer 實例:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
第二個參數是要播放的音檔名稱。使用前必須在專案下新增名為 raw 的資料夾,並把音樂檔放進其中。
建立 MediaPlayer 物件後,可呼叫下列方法來啟動或停止音樂:
mediaPlayer.start(); mediaPlayer.pause();
呼叫 start() 時音樂從頭開始播放;若在 pause() 之後再次呼叫,音樂會從被停住的位置續播,而不是回到開頭。
若要讓音樂從頭開始,必須呼叫 reset() 方法:
mediaPlayer.reset();
除了 start 與 pause,此類別還提供了許多方法,能更完善地處理音訊/影片檔案:
| 方法 | 說明 |
|---|---|
| isPlaying() | 回傳真假值,表示是否正在播放歌曲。 |
| seekTo(position) | 傳入整數,把歌曲移到指定的秒數位置。 |
| getCurrentDuration() | 回傳歌曲目前位置,單位為毫秒。 |
| getDuration() | 回傳歌曲總長度,單位為毫秒。 |
| reset() | 重設媒體播放器。 |
| release() | 釋放 MediaPlayer 物件所占用的任何資源。 |
| setVolume(float leftVolume, float rightVolume) | 設定此播放器的上下聲道音量。 |
| setDataSource(FileDescriptor fd) | 設定音訊/影片檔案的資料來源。 |
| selectTrack(int index) | 傳入整數,選取列表中特定索引的軌道。 |
| getTrackInfo() | 回傳軌道資訊的陣列。 |
以下範例示範如何使用 MediaPlayer 類別,做出一個能快轉、倒轉、播放與暫停歌曲的基本播放器。
要試驗這個範例,需要一台實際裝置才能聽到聲音。
| 步驟 | 說明 |
|---|---|
| 1 | 使用 Android Studio 建立應用程式,命名為 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.Button; import android.widget.EditText; 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) { // Inflate the menu; this adds items to the action bar if it is present. 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/textValue2" android:layout_toRightOf="@+id/textView1" /> <TextView android:id="@+id/textValue1" 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/textValue2" 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/textValue3" 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 手機連上電腦。要從 IDE 執行 App,開啟專案中任一 Activity 檔,點擊工具列上的執行鈕
。在啟動應用之前,IDE 會顯示以下視窗,供選擇要執行 Android 應用的位置。
選擇你的行動裝置作為選項,接著檢查裝置,它會顯示預設畫面:
預設情況下會看到暫停鈕為停用狀態。按下播放鈕後,播放鈕變為停用、暫停鈕變為可用,如下圖:
到目前為止音樂一直在播放。按下暫停鈕並觀察暫停提示,如下圖所示:
此時再按播放鈕,歌曲不會從頭開始,而是從暫停處續播。接著按快轉或倒轉鈕,讓歌曲前進或後退 5 秒。當歌曲已無法再往前跳時,會出現類似這樣的提示:
當你在手機上執行其他工作時,音樂會持續在背景播放。若要讓它停止,必須從背景活動中結束這個應用程式。
Android 登入範例:帳號密碼與重試次數
登入畫面的設計重點一個基本的登入畫面通常包含使用者名稱、密碼與登入按鈕。密碼欄位應使用密碼輸入型態,讓輸入內容以遮罩方式顯示。帳號密碼驗證按下登入鈕後,程式會取得輸入框中
Android 載入 Spinner 教學:ProgressBar 的基本用法
在 Android 中,ProgressBar 除了可顯示確定的進度百分比,也可以用來顯示不確定模式的載入狀態。這種常見的旋轉式載入提示通常被稱為 Spinner。 XM
Android Fragment 入門完全指南(圖文)
Fragment 是什麼 Fragment 從 Android 3.0(API 11)開始引入。可以把 Fragment 想成 Activity 裡的一個模塊:它有自己的
Android JSON 解析:JSONObject 與 JSONArray 的實際應用
JSON 是 Android 開發中常見的資料格式。當 App 需要從網路取得資料時,後端通常會回傳 JSON 字串,開發者再透過 JSONObject 與 JSONAr