i want to add this function in my application, How long did the user watch the video in Exo Player? can anyone tell me this code if is it possible. please solve out this problem.
From ExoPlayer 2.11 you can use PlaybackStatsListener
.
To use PlaybackStatsListener, register an instance with the player by calling player.addAnalyticsListener(playbackStatsListener)
.
Can use playbackStatsListener.playbackStats.totalPlayTimeMs
to get total played duration.
Few notes
Yes it possible, videos' runtime played in ExoPlayer can be easily tracked down.
What you can do
For this example, I used kotlin and ExoPlayer v2.9.3
mPlayer.addListener(object : IPlayerEventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
super.onPlayerStateChanged(playWhenReady, playbackState)
if (playbackState == Player.STATE_READY) {
// Apply some logic here whenever you want to get the duration
var durationMillis = mPlayer.getDuration()
// Apply some logic here to send out the data to your servers (whether after video paused, resumed, stopped, your choice)
// Example (Assuming you use MVVM + RxJava + Retrofit, this is a common way to do network call)
viewModel.uploadPlaybackDetails(userId = 21, videoId = 18, playbackTime = durationMillis)
}
}
override fun onPlayerError(error: ExoPlaybackException?) {
super.onPlayerError(error)
// Handle error here
}
})
Best to get the duration is listening to the ExoPlayer's state changed, especially when it is ready, otherwise if you do this
mPlayer.prepare()
// For example you attempted to get the duration immediately
mPlayer.getDuration()
You will see logs with UNKNOWN_TIME
error.
References
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