Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Handler 讓 SeekBar 跟上音樂:Android MediaPlayer 進階實作

編輯:Android 開發實例

MediaPlayer 只負責「播放」這件事,它不會告訴使用者現在播到哪裡。要讓介面呈現流暢的播放進度,得自己定時去問它目前的位置,再把結果畫到 SeekBar 上。這就是本章範例的核心:一個用 Handler 定時輪詢、能前進後退五秒的完整播放器。

基本播放控制

先用靜態 create() 建立播放器,音樂檔放在 res/raw:

 MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

播放與暫停:

 mediaPlayer.start(); mediaPlayer.pause();

start() 首次呼叫從頭播起;從 pause() 恢復時則接著上次的位置。若要強制回到開頭,先呼叫 reset():

 mediaPlayer.reset();

常用方法

方法說明
isPlaying()是否正在播放。
seekTo(int position)跳到指定毫秒位置。
getCurrentPosition()目前播放位置(毫秒)。
getDuration()總長度(毫秒)。
reset()重設播放器。
release()釋放資源。
setVolume(float, float)設定左右声道音量。
setDataSource(FileDescriptor)指定資料來源。
selectTrack(int index)選取軌道。
getTrackInfo()取得軌道資訊陣列。

範例:具備進度同步的播放器

步驟要做的事
1用 Android Studio 建立 MediaPlayer 專案,套件名 com.yiibai.mediaplayer。
2修改 MainActivity.java 加入播放控制與 Handler 輪詢。
3修改 activity_main.xml 加入四顆 ImageButton 與 SeekBar。
4修改 res/values/string.xml。
5新增 res/raw 資料夾並放入 song.mp3。
6用真機執行,確認有聲音輸出。

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.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.textV4); startTimeField = (TextView)findViewById(R.id.textV1); endTimeField = (TextView)findViewById(R.id.textV2); 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(); } } }

activity_main.xml(省略純樣式屬性):

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageButton android:id="@+id/imageButton3" android:layout_alignParentBottom="true" android:onClick="forward" android:src="@android:drawable/ic_media_ff" /> <ImageButton android:id="@+id/imageButton1" android:layout_toRightOf="@id/imageButton3" android:onClick="play" android:src="@android:drawable/ic_media_play" /> <ImageButton android:id="@+id/imageButton2" android:layout_toRightOf="@id/imageButton1" android:onClick="pause" android:src="@android:drawable/ic_media_pause" /> <ImageButton android:id="@+id/imageButton4" android:layout_toRightOf="@id/imageButton2" android:onClick="rewind" android:src="@android:drawable/ic_media_rew" /> <SeekBar android:id="@+id/seekBar1" android:layout_above="@id/imageButton3" /> <TextView android:id="@+id/textV1" android:text="@string/inital_Time" android:layout_alignTop="@id/seekBar1" /> <TextView android:id="@+id/textV2" android:text="@string/inital_Time" android:layout_alignTop="@id/seekBar1" android:layout_alignParentRight="true" /> <TextView android:id="@+id/textV3" android:text="@string/hello_world" /> <TextView android:id="@+id/textV4" android:layout_alignBaseline="@id/textV3" android:layout_toRightOf="@id/imageButton1" /> </RelativeLayout>

string.xml 與 manifest:

 <resources> <string name="app_name">MediaPlayer</string> <string name="hello_world">Now Playing:</string> <string name="inital_Time">0 min, 0 sec</string> </resources>

<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.mediaplayer"> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

執行流程

接上真機後按下執行 鈕,先選擇要安裝的裝置:

App 啟動後顯示播放器主畫面,此時暫停鈕不可用:

按下播放,播放鈕變灰、暫停鈕亮起,SeekBar 開始往右走:

按下暫停,跳出一個提示訊息,音樂停在原地:

再按播放會從暫停處續播。若一路快轉到接近尾聲,就會看到「無法再往前跳 5 秒」的提示:

實作上有兩點值得留意:Handler 的輪詢間隔若設得太短會讓 UI 一直被 redraw,100 毫秒是相當常見的折衷;另外 Activity 銷毀時記得取消 postDelayed 並呼叫 release(),否則 Runnable 會繼續持有已失效的頁面參考,造成記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved