Example
public class SoundActivity extends Activity {
private MediaPlayer mediaPlayer;
ProgressBar progress_bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tool_sound);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
progress_bar = (ProgressBar) findViewById(R.id.progress_bar);
btn_play_stop.setEnabled(false);
btn_play_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btn_play_stop.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
mediaPlayer.start();
btn_play_stop.setImageResource(R.drawable.ic_play_arrow_black_24px);
}
}
});
mediaPlayer.setDataSource(proxyUrl);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
observer.stop();
progress_bar.setProgress(mp.getCurrentPosition());
// TODO Auto-generated method stub
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
progress_bar.setSecondaryProgress(percent);
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
btn_play_stop.setEnabled(true);
}
});
observer = new MediaObserver();
mediaPlayer.prepare();
mediaPlayer.start();
new Thread(observer).start();
}
private MediaObserver observer = null;
private class MediaObserver implements Runnable {
private AtomicBoolean stop = new AtomicBoolean(false);
public void stop() {
stop.set(true);
}
@Override
public void run() {
while (!stop.get()) {
progress_bar.setProgress((int)((double)mediaPlayer.getCurrentPosition() / (double)mediaPlayer.getDuration()*100));
try {
Thread.sleep(200);
} catch (Exception ex) {
Logger.log(ToolSoundActivity.this, ex);
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
<LinearLayout
android:gravity="bottom"
android:layout_gravity="bottom"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:weightSum="1">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
app:srcCompat="@drawable/ic_play_arrow_black_24px"
android:layout_width="48dp"
android:layout_height="48dp"
android:id="@+id/btn_play_stop" />
<ProgressBar
android:padding="8dp"
android:progress="0"
android:id="@+id/progress_bar"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>
</LinearLayout>