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

Android MediaPlayer:打造自己的音樂播放器

編輯:Android 開發實例

Android 在音訊與影片播放上提供了相當完整的支援,而其中最常被直接使用的一條路徑,就是 MediaPlayer 這個類別。它被封裝在 android.media 套件中,可以播放應用程式內建的資源、SD 卡上的檔案,也能處理網路串流。

用 create() 取得播放器實例

最簡單的起手式是呼叫靜態方法 create(),它會幫你完成建立與設定資料來源兩個動作:

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

第二個參數是要播放的資源。如果音樂檔在專案裡,必須先於 res 底下新增一個名為 raw 的資料夾,把 mp3 放進去,然後用 R.raw.song 這樣的寫法參照它。

播放與暫停

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

行為上有個容易踩到的細節:start() 會從頭開始播;但如果你先呼叫 pause() 再呼叫 start(),播放會從剛剛停下的位置接續,而不是回到開頭。想強制回到起點,得先呼叫 reset():

 mediaPlayer.reset();

其他常用方法

方法說明
isPlaying()回傳布林值,表示目前是否正在播放。
seekTo(position)跳到指定的毫秒位置。
getCurrentPosition()取得目前播放位置(毫秒)。
getDuration()取得整首曲子的總長度(毫秒)。
reset()重設播放器狀態。
release()釋放 MediaPlayer 持有的資源,不呼叫會造成記憶體浪費。
setVolume(left, right)設定左右聲道音量,範圍 0.0 到 1.0。
setDataSource(FileDescriptor)指定音訊或影片的資料來源。
selectTrack(int index)依索引選取特定軌道。
getTrackInfo()回傳軌道資訊陣列。

範例:具備快轉、倒轉的播放器

這個範例做出一個完整的播放介面,包含播放、暫停、前進五秒、後退五秒,以及一條可顯示播放進度的 SeekBar。由於要聽聲音,建議在真機上測試。

步驟做法
1在 IDE 中建立 Android 專案,命名為 MediaPlayer,套件使用 com.yiibai.mediaplayer;Target SDK 與 Compile With 都設為較新的 SDK 版本。
2修改 src/MainActivity.java,加入 MediaPlayer 相關邏輯。
3修改 res/layout/activity_main.xml,放入按鈕與 SeekBar。
4修改 res/values/string.xml,補上字串資源。
5在 MediaPlayer 專案下新增 raw 資料夾,放入名為 song.mp3 的音樂檔。
6執行 App,選擇已連線的裝置並驗證結果。

主活動 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.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) {
        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" />
    <TextView android:id="@+id/textViedw1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/inital_Time" />
    <TextView android:id="@+id/textView2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/inital_Time" />
    <TextView android:id="@+id/textView3" 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>

把真機以 USB 連上電腦,開啟專案的 Activity 檔後按下工具列上的執行鈕:

IDE 接著會詢問要在哪裡執行,此時選擇你的行動裝置:

App 啟動後就是這個預設畫面:

可以注意到,初始狀態下暫停鈕是灰的。按下播放鈕後,播放鈕變灰、暫停鈕轉為可用:

此時音樂正在播放。按下暫停鈕會看到提示訊息:

再按一次播放鈕,曲子會從剛才暫停的位置繼續,而不是跳回開頭。接著可以試試快轉或倒轉鈕,每次跳 five 秒;當已經快到曲子尾端、無法再往前跳時,會跳出提示訊息:

另外值得一提的是,當你切到其他 App 做事時,音樂仍會在背景持續播放。若要讓它停下來,得把這個應用從背景工作列表中移除。

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