I'm trying to play mp3 file from url with ExoPlayer
.
Everything is fine but now I wonder when is the time it's safe to getDuration()
of the audio track. I just need it once track is loaded. Didn't find it in google's example project.
When I try to get it immediately after exoPlayer.prepare()
then I get UNKNOWN_TIME
.
ExoPlayer is an application level media player for Android. It provides an alternative to Android's MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android's MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks.
Android StudioOpen the ExoPlayer project, navigate to the playbacktests module, right click on the gts folder and run the tests. Test results appear in Android Studio's Run window.
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.
}
});
private int getVideoDurationSeconds(SimpleExoPlayer player)
{
int timeMs=(int) player.getDuration();
int totalSeconds = timeMs / 1000;
return totalSeconds;
}
just call this method with exoplayer object and you will find total seconds
complete method
private String stringForTime(int timeMs) {
StringBuilder mFormatBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
int totalSeconds = timeMs / 1000;
// videoDurationInSeconds = totalSeconds % 60;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With