Search code examples
androidmp3media-player

MediaPlayer completes after pausing


I recently observed a very weird problem with MediaPlayer playing an mp3 file. I'm running this code (mPlayer is a MediaPlayer):

Log.d(TAG, "Pausing");
try {
    mPlayer.pause();
    Log.d(TAG, "Paused");
} catch (IllegalStateException e) {
    Log.w(TAG, "exception pausing player");
}

The weird thing is that if I'm close to the end of the audio file, the player sends a completion notification to my OnCompletionListener a short time after the above code completes. (I haven't pinned down exactly how close I have to be, but it's on the order of 1/4 second.) For instance, here's a typical logcat output when this occurs:

05-27 17:23:43.439: DEBUG/Player(266): Pausing
05-27 17:23:43.487: DEBUG/Player(266): Paused
05-27 17:23:43.838: WARN/Player(266): Audio completed (state=PAUSED)

Note that the warning line (logged from my OnCompletionListener), comes over 300 ms after the call to pause() returned!

The result is that the media player enters the PlaybackCompleted state when I don't expect it. This screws up the behavior of my code (as well as start(), which restarts from the beginning instead of playing the last little bit of the file).

This has happened on emulators from 1.6 through 2.3 and on at least one device running 2.2. Does anyone know about this problem and what to do about it?


Solution

  • The mediaplayer runs in a separate thread and you have to wait until the ui thread and the mediaplayer's thread have synced. So the delay is normal. It may be possible that the player really completes the file because of your pause-command reaching the player too late. Try what happens with a longer audio-file.

    Another problem which might come up is other code seeking beyond the end of the track after the pause-command. What's the code of your listener?