引言:做过音视频开发都知道缓存对于提升播放体验和开播效率的重要影响。今天分享一个缓存机制:音视频库Exoplayer的默认缓存(CacheDataSource),我认为是目前开源库中最优秀的缓存机制(学识有限哈)
**功能简单实现 :
fun cache(videoUrl: String, cacheSize: Long = 512 * 1024) {
if (mCachedList.contains(videoUrl)) return
LogUtils.d(TAG, "$videoUrl cache $cacheSize start")
priorityTaskManager.add(C.PRIORITY_DOWNLOAD)
val dataSpec = DataSpec(Uri.parse(videoUrl), 0, cacheSize, null)
try {
CacheUtil.cache(
dataSpec,
mVideoCache,
writeFactory.createDataSource(),
byteArray,
priorityTaskManager,
C.PRIORITY_DOWNLOAD,
null,
null,
false)
LogUtils.d(TAG, "$videoUrl cache $cacheSize end")
} catch (e: Exception) {
LogUtils.d(TAG, "$videoUrl cache $cacheSize exception: ${e.message}")
mCachedList.remove(videoUrl)
} finally {
mCachedList.add(videoUrl)
priorityTaskManager.remove(C.PRIORITY_DOWNLOAD)
}
}
抽出功能缓存类 : https://download.csdn.net/download/weixin_46728351/86512162
https://download.csdn.net/download/weixin_46728351/85982828
Exoplayer引用:播放器和缓存工具类使用同一个SimpleCache实例即可
需要支持后台下载和前台播放优先级使用同一个PriorityTaskManager
val dataFactory = CacheDataSourceFactory(
mVideoCache,
DefaultHttpDataSourceFactory("video"),
CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR or CacheDataSource.FLAG_BLOCK_ON_CACHE,
CACHE_SIZE_SINGLE_VIDEO_FILE_MAX)
val videoSource = ExtractorMediaSource.Factory(dataFactory)
.setExtractorsFactory(DefaultExtractorsFactory())
.createMediaSource(Uri.parse(url))
exoMediaPlayer.setDataSource(videoSource)`**