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

用 MediaPlayer 做一個 Android 音樂播放器

編輯:Android 開發實例

要在 Android 上播放音訊或影片,最直接的方式就是走 MediaPlayer。它位於 android.media 套件,能播放應用程式內的資源、裝置上的檔案,也能處理網路串流。這個類別背後其實是封裝好的原生播放服務,因此不必自己處理解碼細節。

取得 MediaPlayer 實例

最省事的做法是呼叫靜態的 create(),它一次完成建立物件與指定資料來源:

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

第二個參數是資源識別碼。若音樂檔要放在專案內,需在 res 下新增名為 raw 的資料夾,把檔案丟進去即可。

開始與暫停

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

行為上要注意:start() 首次呼叫會從頭播起;但若在 pause() 之後再呼叫 start(),會從暫停處續播。想回到開頭,得先 reset():

 mediaPlayer.reset();

常用方法一覽

方法說明
isPlaying()回傳是否正在播放。
seekTo(position)跳至指定毫秒位置。
getCurrentPosition()目前播放位置(毫秒)。
getDuration()總長度(毫秒)。
reset()重設播放器。
release()釋放資源,Activity 銷毀時建議呼叫。
setVolume(left, right)設定左右声道音量(0.0–1.0)。
setDataSource(FileDescriptor)指定資料來源。
selectTrack(int index)依索引選取軌道。
getTrackInfo()取得軌道資訊陣列。

範例:含快轉倒轉與進度條的播放器

這個範例做出一個可用的播放介面:播放、暫停、前後各跳五秒,並以 SeekBar 即時顯示進度。建議用真機測試才聽得到聲音。

步驟做法
1建立 Android 專案 MediaPlayer,套件 com.yiibai.mediaplayer,Target SDK 與 Compile With 設為較新版本。
2修改 src/MainActivity.java 加入播放邏輯。
3修改 res/layout/activity_main.xml 加入控制元件。
4修改 res/values/string.xml 加入字串。
5在專案下建立 raw 資料夾,放入 song.mp3。
6執行並在裝置上驗證。

主活動 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.textViedw4);
        startTimeField = (TextView)findViewById(R.id.textViedw1);
        endTimeField = (TextView)findViewById(R.id.textViedw2);
        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/textViedw2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/inital_Time" />
    <TextView android:id="@+id/textViedw3" 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 啟動後顯示預設畫面:

此時暫停鈕是停用狀態。按下播放鈕,兩顆按鈕的啟用狀態會互換:

音樂開始播放後,按暫停鈕會看到對應的提示:

再按播放鈕,曲子會從暫停的位置續播。試著按快轉或倒轉,每次移動五秒;當再往前就會超出總長度時,會跳出提示:

最後一個實務提醒:即使你切去其他 App,音樂仍會在背景繼續播放。要真正停止,必須把這個應用從背景的活動列表中結束掉。

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