MediaPlayer seekTo inconsistently plays songs from

2019-05-07 03:38发布

问题:

I'm using Android's MediaPlayer class to start playing a song from some offset. After specifying this offset in code, I play the song expecting to hear it from that offset position but rather I hear it play from the beginning. Please note the following code:

    MediaPlayer mplayer = new MediaPlayer();
    mplayer.reset();
    try {
        // For example's sake, specify some known song path
        mplayer.setDataSource("//media/external/audio/media/1");
        // call blocking prepare()
        mplayer.prepare();
    } catch (Exception e) {
    // Keep try/catch simple for example's sake
        e.printStackTrace();
        return;
    }

    // seekTo is an asynchronous operation. Set it's complete callback to play the song once seekTo has completed
    mplayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(MediaPlayer mp) {
            // Start the song 30 seconds in
            mp.start();
        }
    });
    // Seek to 30 seconds into the song
    mplayer.seekTo(30000);

This code sample runs without errors in the emulator (tested against Android 1.6, 2.1, and 2.2); however, when run on some handsets, the song will play from the beginning. I know for sure this happens on my Droid Incredible (android 2.2). Also note that LogCat will always have some output from the MediaPlayer class stating the song's position has indeed been set to some offset. I've debugged this for hours and scoured forums and still have no solution. Please help.

回答1:

In case you haven't found it on your own by now, this is a buffering problem (issue documented here). Seeking to a non-buffered position results in playing from the beginning instead. The proposed solutions are found here (not the most elegant, but about all there is to do).