I have spent lots of hours trying to figure this out:
When MediaPlayer is loaded and started the first time, its OnCompletion is called. This is a prob开发者_如何学Golem because I have some code that skips to the next track when the previous track is finished.
I have solved it using a flag in the OnCompletion listener, but why is it like that?
This snippet is from the play() method in my service:
mp.setDataSource(mCurrentMediaFile);
mp.prepare();
mDuration = mp.getDuration();
int seek = mDuration * position / 1000;
mp.seekTo(seek);
mp.start();
For some reason, onCompletion is called right after returning from the play() method even though it's the first track being played after the service is created.
The only reason I see for such behaviour, in the provided code, is a bad seek value from the line int seek = mDuration * position / 1000;
. Log the value out to check it out.
You should try placing your mp.seekTo code in the onPrepared callback. If the seek value is taken in to effect before the onPrepared callback, the seek value gets reset by the MediaPlayer. Lastly, the media needs to be buffered correctly before knowing what position to seek to. The onPrepared callback ensures this.
Hope that helps!
In my case, I've figured out that after mp.start() had been called, mp raised an error with the code -38, triggered the onCompletion call. To fix this just implement onCompletionListener and return true, as below code:
mediaPlayer.setOnErrorListener { p0, p1, p2 ->
Log.d("MP", "Error code: p1 $p1 - p2 $p2")
true
}
https://developer.android.com/reference/android/media/MediaPlayer.OnErrorListener
Returning false, or not having an OnErrorListener at all, will cause the OnCompletionListener to be called.
Still can't get why the error happened and which error has value of (-38). Couldn't believe this issue has wandered around for more than 10 years...
精彩评论