我想在我的应用程序中添加这个功能,用户在 Exo Player 中观看视频多长时间了?谁能告诉我这段代码是否可能。请解决这个问题。
最佳答案
一些笔记
是的,可以很容易地追踪在 ExoPlayer 中播放的视频的运行时间。
你能做什么
对于这个例子,我使用了 kotlin 和 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
}
})
最好的持续时间是监听 ExoPlayer 的状态改变,尤其是当它准备好时,否则如果你这样做
mPlayer.prepare()
// For example you attempted to get the duration immediately
mPlayer.getDuration()
您将看到带有 UNKNOWN_TIME
错误的日志。
引用资料
关于android - 跟踪用户观看视频 android exoplayer 的时长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54375236/