CacheDataSource
and SimpleCache
实现两个不同的目的。如果你看一下他们的类原型,你会发现CacheDataSource implements DataSource
and SimpleCache implements Cache
。当您需要缓存下载的视频时,您必须使用CacheDataSource
身为你的DataSource.Factory
准备媒体播放:
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, "AppName"));
dataSourceFactory = new CacheDataSourceFactory(VideoCacheSingleton.getInstance(), dataSourceFactory);
然后使用dataSourceFactory
创建一个MediaSource
:
// This is the MediaSource representing the media to be played.
MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(mediaUri);
SimpleExoPlayer exoPlayerInstance = new SimpleExoPlayer.Builder(context).build();
exoPlayerInstance.prepare(mediaSource);
While SimpleCache
为您提供一个维护内存中表示的缓存实现。正如您在第一个代码块中看到的,CacheDataSourceFactory 构造函数需要一个Cache
要使用的实例。您可以声明自己的缓存机制或使用默认的SimpleCache
ExoPlayer 为您提供的类。如果您需要使用默认实现,您应该记住这一点:
给定目录在给定时间只允许有一个 SimpleCache 实例
根据文档 https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/upstream/cache/SimpleCache.html。所以为了使用单个实例SimpleCache
对于文件夹,我们使用单例声明模式:
public class VideoCacheSingleton {
private static final int MAX_VIDEO_CACHE_SIZE_IN_BYTES = 200 * 1024 * 1024; // 200MB
private static Cache sInstance;
public static Cache getInstance(Context context) {
if (sInstance != null) return sInstance;
else return sInstance = new SimpleCache(new File(context.getCacheDir(), "video"), new LeastRecentlyUsedCacheEvictor(MAX_VIDEO_CACHE_SIZE_IN_BYTES), new ExoDatabaseProvider(context)));
}
}
TL; DR
We use CacheDataSource
准备缓存媒体播放和SimpleCache
来建立其DataSource.Factory
实例。