我对 ExoPlayer 及其文档非常困惑。谁能解释一下我们应该出于什么目的以及何时使用 CacheDataSource 和 SimpleCache?
CacheDataSource
和 SimpleCache
实现两个不同的目的。如果你看一下他们的类原型,你会看到 CacheDataSource implements DataSource
和 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);
而
SimpleCache
为您提供了一个维护内存中表示的缓存实现。正如您在第一个代码块中看到的,CacheDataSourceFactory 构造函数需要一个 Cache
实例才能使用。您可以声明自己的缓存机制或使用 ExoPlayer 为您提供的默认 SimpleCache
类。如果您需要使用默认实现,您应该记住这一点:
在给定时间给定目录只允许有一个 SimpleCache 实例
根据文档。因此,为了对文件夹使用
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)));
}
}
我们使用
CacheDataSource
准备缓存媒体播放,并使用 SimpleCache
构建其 DataSource.Factory
实例。