Florian
Florian

Reputation: 33

Update progress bar with media player

I tried to use the MediaPlayer and display the current position in the ProgressBar. The media player itself works, but the ProgressBar displays nothing. Below is the code:

final Uri fileUri = Uri.fromFile(audioFile);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
new Thread(new Runnable() {

    @Override
    public void run() {
        try {
            mp.setDataSource(getApplicationContext(), fileUri);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}).start();


progress = findViewById(R.id.audioProgressBar);
audioDuration = mp.getDuration();
progress.setMax(100);

new Thread(new Runnable() {

        @Override
        public void run() {
            while (progressStatus <= audioDuration) {
                progressStatus += 1;
                handler.post(new Runnable() {
                    public void run() {
                        float progressFloat = ((float) mp.getCurrentPosition() / mp.getDuration()) * 100;
                        progress.setProgress((int) progressFloat);
                    }
                });
                try {
                    // Sleep for 200 milliseconds.
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

I hope you can help me!

Upvotes: 0

Views: 5454

Answers (1)

udit7395
udit7395

Reputation: 626

Since you are initializing mediaPlayer in different thread, the value you might be getting getDuation might be empty or incorrect as well since you do not know for sure whether mediaPlayer is initialized or not.

Try using the following method as it will eliminate the method of setting Max progress again and again(since different song lengths hence setMax will change).

Set progress max to 100 instead of audioDuration.

progress.setMax(100);

Then in your handler calculate progress as follows

//current value in the text view
handler.post(new Runnable() {
    public void run() {
        //Calculate progress
        float progress = ((float) mp.getCurrentPosition() / mp.getDuration()) * 100;

        progress.setProgress((int) progress);
    }
});

Upvotes: 1

Related Questions