播放MP3,設置進度條
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
mp3檔案放置在res\raw裡面
![](2015-12-25_153301.jpg)
※progress.setMax必須放在player.start();後面
package com.example.app27;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progress;
MediaPlayer player;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressBar) this.findViewById(R.id.progressBar1);
player = MediaPlayer.create(this, R.raw.stripme);
player.start();
progress.setMax(player.getDuration());
handler = new Handler();
handler.post(updateProgress);
}
Runnable updateProgress = new Runnable() {
@Override
public void run() {
progress.setProgress(player.getCurrentPosition());
handler.postDelayed(updateProgress, 50);
}
};
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updateProgress);
player.stop();
player.release();
}
}