I'm making an app where I play .mp3 files from the URL. I'm using the latest version of ExoPlayer 2.11.4.
What I need to do is get the total duration of the audio from the url so I can use it in my custom audio player.
The urls I'm using are of this type: https://myserver.net/.../audio/439688e0c3626d39d3ef3.mp3?token=6oz-22-2sa-9yh-7e-2iak
The problem is that sometimes my code works correctly most of the time and returns the correct duration. But sometimes what I get is a negative number: -9223372036854775807
And that doesn't allow my code to work properly. My code where I get the duration is this:
fun getDuration(url: String, context: Context) {
exoPlayer?.release()
exoPlayer = SimpleExoPlayer.Builder(context).build()
val dataSourceFactory = DefaultDataSourceFactory(context, Util.getUserAgent(context, "ExoPlayer"))
val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(url))
exoPlayer?.prepare(mediaSource)
exoPlayer?.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playbackState == ExoPlayer.STATE_READY) {
val realDurationMillis: Long? = exoPlayer?.getDuration()
currentDuration = realDurationMillis
if (currentDuration != null) {
if (currentDuration!! > 0) {
exoPlayer?.release()
}
}
}
}
})
}