上篇文章我简单介绍了基于2.18.2的Exoplayer的基本使用,这篇文章将介绍2.18.2版本下的Exoplayer缓存使用。
请注意,这里使用的是Exoplayer自带的缓存机制,并不是使用的三方库
江湖规矩,直接上代码
- 缓存工厂创建
object MediaCacheFactory {
private const val TAG = "MediaCacheFactory"
private var cacheFactory: DataSource.Factory? = null
private val sDatabaseProvider: DatabaseProvider? = null
@Synchronized
fun getCacheFactory(ctx: Context): DataSource.Factory {
if (cacheFactory == null) {
var downDirectory = File(ctx.cacheDir, "videos")
var cache = SimpleCache(
downDirectory,
LeastRecentlyUsedCacheEvictor(1024 * 1024 * 512),
null
)
cacheFactory = CacheDataSource.Factory().setCache(cache)
.setCacheReadDataSourceFactory(
DefaultDataSource.Factory(
ctx,
DefaultHttpDataSource.Factory().setAllowCrossProtocolRedirects(false)
.setConnectTimeoutMs(8000)
.setReadTimeoutMs(8000)
.setUserAgent("MY_Exoplayer")
)
)
.setUpstreamDataSourceFactory(
DefaultHttpDataSource.Factory().setAllowCrossProtocolRedirects(false)
.setConnectTimeoutMs(8000)
.setReadTimeoutMs(8000)
.setUserAgent("MY_Exoplayer")
)
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
.setEventListener(object : CacheDataSource.EventListener {
override fun onCachedBytesRead(cacheSizeBytes: Long, cachedBytesRead: Long) {
Log.d(TAG, "onCachedBytesRead $cacheSizeBytes >> $cachedBytesRead")
}
override fun onCacheIgnored(reason: Int) {
Log.d(TAG, "onCacheIgnored $reason")
}
})
}
return cacheFactory!!
}
}
- 缓存工厂的使用
val player = ExoPlayer.Builder(this).build()
playerView.player = player
val contentUri = Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
val mediaItem = MediaItem.fromUri(contentUri)
val mediaSource: ProgressiveMediaSource = ProgressiveMediaSource.Factory(MediaCacheFactory .getCacheFactory(context.applicationContext)).createMediaSource(mediaItem)
player.setMediaSource(mediaSource)
player.playWhenReady = true
player.prepare()
总结
至此就完成了Exoplayer自带缓存的使用,下次再次播放相同视频的时候,即使是没有网络,也能轻松加载播放。
如果我的文章有帮助到你,麻烦一键三连,收藏点赞转发,Peace guys