我对 ExoPlayer 及其文档感到很困惑。请解释一下我们应该使用 CacheDataSource 的目的是什么,什么时候使用 SimpleCache?
最佳答案
CacheDataSource
和 SimpleCache
实现两个不同的目的。如果您查看他们的类原型(prototype),您会发现 CacheDataSource 实现了 DataSource
并且 SimpleCache 实现了 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
类。如果您需要使用默认实现,您应该牢记这一点:
Only one instance of SimpleCache is allowed for a given directory at a given time
根据 documentation .因此,为了对文件夹使用 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;博士
我们使用 CacheDataSource
准备缓存媒体播放,并使用 SimpleCache
构建其 DataSource.Factory
实例。
关于android - exoplayer 中的 CacheDataSource 与 SimpleCache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63883690/