DCoder DCoder - 3 months ago 30
Android Question

Smoothly increase progress bar while playing audio file

I am playing audio file of different sizes in my application and while audio is playing the progress bar should progress smoothly but progress bar is taking random size steps.

I am using following code :

mp = new MediaPlayer();
mp.setDataSource("audio file path");
mp.prepare();
mp.start();
pb.setMax(mp.getDuration());
new AsyncTask<Void, Integer, Void>() {
@Override
protected Void doInBackground(Void... params) {
while(mp.isPlaying())
{
publishProgress(mp.getCurrentPosition);
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
pb.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mp.stop();
mp.release();
}
}.execute();


Is there any way to smoothly increase progressbar?

Answer

Please check this steps

Step 1: Get audio duration with MediaPlayer.getDuration()

Step 2: Set ProgressBar progress max. value to value from step 1

Step 3:

Update progress bar periodically from MediaPlayer.getCurrentPosition(), while media playing using Handler.

So the code will be like this

MediaPlayer mMediaPlayer = new MediaPlayer();
    final SeekBar mSeelBar = new SeekBar(this);
    final int duration = mMediaPlayer.getDuration();
    final int amoungToupdate = duration / 100;
    Timer mTimer = new Timer();
    mTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (!(amoungToupdate * mSeelBar.getProgress() >= duration)) {
                        int p = mSeelBar.getProgress();
                        p += 1;
                        mSeelBar.setProgress(p);
                    }
                }
            });
        };
    }, amoungToupdate);

I followed this link for the code

Comments