編輯:Android 開發實例
Android 透過 MediaPlayer 類別讓開發者得以存取系統內建的媒體播放服務,例如播放音樂、影片等。要使用 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 還提供了許多實用方法,能更靈活地處理音訊與影片,整理如下:
以下範例示範如何使用 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/text2" android:layout_toRightOf="@+id/text1" /> <TextView android:id="@+id/text1" 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/text2" 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/text3" 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/text3" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/text4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/text3" android:layout_alignBottom="@+id/text3" 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 中開啟專案的任一活動檔案,點擊工具列上的執行
圖示。在正式啟動前,Eclipse 會先跳出視窗讓你選擇要執行應用的目標。
選擇你的手機作為執行目標,接著查看手機畫面,會看到如下的預設介面:
預設情況下,暫停按鈕是無法點擊的。按下播放按鈕後,它會變為不可點,而暫停按鈕則被啟用,如下圖所示:
此時音樂正在播放。按下暫停按鈕,你會看到暫停的提示訊息,如下圖:
再次按下播放按鈕時,歌曲不會從頭開始,而是從剛才暫停的位置續播。接著可按快轉或倒退按鈕,讓歌曲前進或後退 5 秒。當歌曲無法再往前跳轉時,就會跳出類似如下的提示:
即使你在手機上進行其他操作,音樂仍會在背景持續播放。若想停止,必須從背景活動中結束這個應用。
Android 示例程式剖析之 Snake 貪吃蛇(二:FrameLayout 與 RelativeLayout)
本文以 Snake 專案為例,說明 FrameLayout 與 RelativeLayout 的差異,並示範如何用 merge 標籤減少多餘的版面節點。FrameLayo
Android 登入頁面教學:從輸入驗證到錯誤鎖定
只要 App 涉及使用者帳號,就少不了登入畫面。它看似簡單,其實要處理的細節不少:密碼要遮蔽、驗證要正確、錯誤要提示,還得防止有人一直試密碼。本章依序把這些環節做完。 建
Android 教學:實作介面跳動提示動畫效果
本文要說明如何實作一個「介面跳動提示」的動畫效果,藉由讓頁面上緣微微跳動,暗示使用者可以往上拉動來切換頁面。先來看效果圖:先來看版面配置: <RelativeLay
Android 在地化實務:從 strings.xml 到語言切換
在地化的意義在地化不只是翻譯文字,也包括讓應用符合不同地區使用者的閱讀習慣。最常見的做法,是將畫面文字集中管理,並依語言提供不同資源。資源資料夾結構預設字串通常放在 re