編輯:Android 開發實例
Android 的 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,這個類別還提供了許多方法,能更細緻地處理音訊與影片:
以下範例示範如何使用 MediaPlayer 類別,打造一個能播放、暫停、快轉與倒轉歌曲的簡易播放器。
由於要實際聆聽聲音,建議在實體裝置上運行這個範例。
以下是修改後的主程式 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/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>
以下是 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 App。假設你已將實體 Android 手機連上電腦,在 Eclipse 中開啟專案的任一 Activity 檔,點擊工具列上的執行
圖示。啟動前,Eclipse 會先跳出視窗讓你選擇要執行 App 的目標。
選擇你的手機裝置後,畫面會顯示播放器的預設樣式:
此時你會看到暫停鈕預設是停用的。按下播放鈕後,播放鈕會轉為停用、暫停鈕則啟用,如下圖:
到目前為止音樂一直在播放。按下暫停鈕,就會看到暫停提示,如下圖:
再次按下播放鈕時,歌曲不會从头開始,而是從剛才暫停的位置續播。你也可以按快轉或倒轉鈕,讓歌曲前後跳轉 5 秒。當歌曲已無法再往前跳時,就會跳出類似下圖的提示:
即使你切去執行手機上的其他工作,音樂仍會在背景持續播放。若要停止,就得從背景活動中結束這個 App。
TableLayout 常用屬性:collapseColumns、shrinkColumns、stretchColumns
TableLayout 是 Android 中常用的表格版面。它透過列與欄的方式排列控制項,並提供多個欄位調整屬性,例如隱藏、延伸與填滿。理解這些屬性能有效解決複雜對齊問
Android 載入 Spinner 進度轉圈動畫教學
在 Android 中,想向使用者呈現某項工作正在進行,可以透過進度條來表達。進度條大致分成兩種樣式:一種是帶有進度的水平進度列,另一種則是不斷旋轉的載入轉圈(Spinn
Android 開發實作:ListView 與 GridView 用法全解析
ListView 與 GridView 是 Android 開發裡最常被使用的兩個檢視元件,兩者都必須搭配 Adapter 才能發揮作用。本文以兩個可運行的實例,分別說明
Android ToggleButton 控件使用詳解(開燈關燈實例)
ToggleButton 是一個只有兩種狀態的開關按鈕:選中與未選中。它最大的特點是可以為這兩種狀態分別指定顯示文字,因此非常適合用來表達「開/關」「是/否」這類二元選擇