ExoPlayer,概括 SimpleCache 行为

Mas*_*imo 5 android exoplayer

我正在使用 ExoPlayer 2 从网络播放音乐。现在我想使用美丽的SimpleCache类来缓存下载的音乐。我的问题如下:每次我请求播放歌曲时,服务器都会向我返回一个不同的 URL(也用于同一首歌曲),该 URL 用作SimpleCache. 因此,SimpleCache为每个 URL 创建一个新的缓存文件(即对于同一首歌曲也创建一个不同的文件)。

如果有办法问我为特定 url 生成的缓存文件的键是什么,那就太好了。你知道一种方法吗?

SimpleCache班是final的,所以我不能重写它的方法。


编辑,一个粗略的解决方案:
我创建了一个副本CacheDataSource并更改了方法中的这一行open(DataSpec),它负责密钥的生成:

key = dataSpec.key != null ? dataSpec.key : uri.toString();
Run Code Online (Sandbox Code Playgroud)

由于 someuri的参数,我可以生成相同的密钥,这些参数对于为同一首歌曲检索的每个 url 都是相等的。这个解决方案解决了我的问题,但对于每种可能的情况都不是那么通用和可利用的。

CacheDataSource已经然后用作解释此评论

private DataSource.Factory buildDataSourceFactory(final boolean useBandwidthMeter) {
    return new DataSource.Factory() {
        @Override
        public DataSource createDataSource() {
            LeastRecentlyUsedCacheEvictor evictor = new LeastRecentlyUsedCacheEvictor(100 * 1024 * 1024);
            SimpleCache simpleCache = new SimpleCache(new File(getCacheDir(), "media_cache"), evictor);
            return new CacheDataSource(
                simpleCache,
                buildMyDataSourceFactory(useBandwidthMeter).createDataSource(),
                CacheDataSource.FLAG_BLOCK_ON_CACHE,
                10 * 1024 * 1024
            );
        }
    };
}

private DefaultDataSource.Factory buildMyDataSourceFactory(boolean useBandwidthMeter) {
    return new DefaultDataSourceFactory(PlayerActivity.this, userAgent, useBandwidthMeter ? BANDWIDTH_METER : null);
}
Run Code Online (Sandbox Code Playgroud)

Mas*_*imo 3

从 ExoPlayer 2.10.0 开始,添加了该类ProgressiveMediaSource,它取代了ExtractorMediaSource(已弃用)。当使用其类创建 ProgressiveMediaSource 时,Factory您可以调用该方法setCustomCacheKey(String)

它正是我所需要的!