MediaPlayer.seekTo() does not work for unbuffered

2019-01-18 22:38发布

问题:

I use MediaPlayer for playing a single mp3 song from network. Data source is a HTTP URL.

Let's assume we have following playing state.

Song duration: 1:00

Current progress: 0:10

Current buffering progress 0:30

Let's say I want to skip some part of a song and seek forward. I do it with MediaPlayer.seekTo() method. If I seek to buffered position (0:20) it is performed correctly. But if I seek to a position which has not been buffered yet (0:40) the MediaPlayer behaves odd. It indicates immediately that it has seeked correctly without waiting for a buffer to fill. In fact it continues playing at the same position where it was before seeking. From now on MediaPlayer.getCurrentPosition() method returns wrong position. When playing reaches its end and OnCompletionListener.onCompletion callback is called the current media player position is much higher than entire song duration.

Any ideas for solving this?

回答1:

It's probably related to the bug that's (referring to one of the comments) eventually fixed in 2.2 http://code.google.com/p/android/issues/detail?id=4124



回答2:

I found a workaround for this problem:

First you create an OnBufferingUpdateListener:

MediaPlayer.OnBufferingUpdateListener bufferingListener = new MediaPlayer.OnBufferingUpdateListener() {
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        //code to increase your secondary seekbar
    }
};

Then in your seekbar event onProgressChanged do the following:

public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
    int secondaryPosition = seekBar.getSecondaryProgress();
    if (progress > secondaryPosition)
        seekBar.setProgress(secondaryPosition);
}

With this you guarantee the user can't drag the progress bar to an unbuffered position (and also you see what's buffered).



回答3:

It has been fixed in Android 2.2 in some devices only as far as I know.

However Android 2.2 messes up with seeking to buffered posistion. Although a position is already buffered MediaPlayer sends a request to a server.