I'm trying to play mp3 file from URL with ExoPlayer
.
Everything is fine, but now I wonder when is the it is safe to call getDuration()
of the audio track. I just need it once the track is loaded. I didn't find it in Google's example project.
When I try to get it immediately after exoPlayer.prepare()
then I get UNKNOWN_TIME
.
Ok, looks like this is the only solution here.
We add listener to our player, and get duration when state changes to STATE_READY
. It will obviously called on every play/pause action so we need to wrap it with boolean durationSet
flag if
check to call it once on track start. Then durationSet = false
somewhere near audioPlayer.prepare()
audioPlayer.addListener(new ExoPlayer.Listener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_READY && !durationSet) {
long realDurationMillis = audioPlayer.getDuration();
durationSet = true;
}
}
@Override
public void onPlayWhenReadyCommitted() {
// No op.
}
@Override
public void onPlayerError(ExoPlaybackException error) {
// No op.
}
});