Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track how long a user has watched a video android exoplayer

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.

like image 774
Azeem Ahmad Avatar asked Sep 06 '25 09:09

Azeem Ahmad


2 Answers

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.

like image 145
Chethan N Avatar answered Sep 09 '25 20:09

Chethan N


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

  • https://github.com/google/ExoPlayer
like image 35
Joshua de Guzman Avatar answered Sep 09 '25 19:09

Joshua de Guzman