我正在使用 ExoPlayer 2 播放来自网络的音乐。现在我想通过使用漂亮的 SimpleCache
类来缓存下载的音乐。我的问题如下:每次我请求播放歌曲时,服务器都会返回一个不同的 URL(也是针对同一首歌曲),SimpleCache
将其用作键。因此,SimpleCache
为每个 URL 创建一个新的缓存文件(即同一首歌曲的不同文件)。
如果有一种方法可以询问我为特定 url 生成的缓存文件的 key 是什么,那就太好了。你知道这样做的方法吗?
SimpleCache
类是final
,所以我不能覆盖它的方法。
编辑,一个粗略的解决方案:
我创建了 CacheDataSource
的副本,并在方法 open(DataSpec)
中更改了这一行,它负责生成 key :
key = dataSpec.key != null ? dataSpec.key : uri.toString();
由于一些 uri
的参数,我可以生成相同的 key ,这些参数对于为同一首歌曲检索的每个 url 都是相等的。此解决方案解决了我的问题,但并不是对所有可能的情况都如此通用和可利用。
然后按照 this comment 中的说明使用了 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);
}
最佳答案
从 ExoPlayer 2.10.0 开始,它添加了 ProgressiveMediaSource
类,它取代了 ExtractorMediaSource
(已弃用)。
使用 Factory
类创建 ProgressiveMediaSource 时,您可以调用方法 setCustomCacheKey(String)
。
它完全符合我的需要!
关于android - ExoPlayer,泛化 SimpleCache 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42073937/