The answer of pavelkorolevxyz works well if you have a single media item in the track, but if there are multiple items/files, it would be a cumbersome to get around the if (playbackState == ExoPlayer.STATE_READY && !durationSet)
condition and to reset the durationSet
for the new media file.
We'd better change that by Media3 ExoPlayer API onMediaItemTransition()
callback for the upcoming media files:
var mediaDuration = 0L // inital value is 0 before starting the player
val listener = object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == ExoPlayer.STATE_READY && mediaDuration == 0) {
// The player is just run, and this is the 1st MediaItem duration
mediaDuration = exoPlayer.duration
}
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
super.onMediaItemTransition(mediaItem, reason)
// Media Transition, this is another mediaItem beyond the first one
mediaDuration = exoPlayer.duration
}
}
// register the listener
exoPlayer.addListener(listener)
Then you could reset mediaDuration = 0L
when releasing the player resources.