exoplayer 中的 CacheDataSource 与 SimpleCache?

nir*_*rma 4 android exoplayer2.x

我对 ExoPlayer 及其文档非常困惑。谁能解释一下我们应该出于什么目的以及何时使用 CacheDataSource 和 SimpleCache?

Sdg*_*emi 5

CacheDataSourceSimpleCache实现两个不同的目的。如果您查看他们的类原型,您会看到CacheDataSource implements DataSourceSimpleCache 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);
Run Code Online (Sandbox Code Playgroud)

然后使用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);
Run Code Online (Sandbox Code Playgroud)

虽然为SimpleCache您提供了一个维护内存中表示的缓存实现。正如您在第一个代码块中看到的,CacheDataSourceFactory 构造函数需要一个Cache实例才能使用。您可以声明自己的缓存机制或使用SimpleCacheExoPlayer 为您提供的默认类。如果您需要使用默认实现,您应该记住这一点:

给定目录在给定时间只允许有一个 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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

TL; DR

我们用来CacheDataSource准备缓存媒体播放并SimpleCache构建其DataSource.Factory实例。