android - 在 ExoPlayer 中使用缓存

标签 android caching media exoplayer

我正在寻找在 ExoPlayer 中实现缓存的任何示例。

ExoPlayer 在它的库中有不同的关于缓存和谷歌的类在这个 video 中解释。我们可以用 CacheDataSource 类来实现它,但谷歌没有提供任何关于它的演示。不幸的是,这似乎使用起来相当复杂,所以我目前正在寻找示例(在 Google 上没有成功)。

有没有人成功或有任何有用的信息?谢谢。

最佳答案

这是 ExoPlayer 2.+ 的解决方案

创建自定义缓存数据源工厂

public class CacheDataSourceFactory implements DataSource.Factory {
    private final Context context;
    private final DefaultDataSourceFactory defaultDatasourceFactory;
    private final long maxFileSize, maxCacheSize;

    public CacheDataSourceFactory(Context context, long maxCacheSize, long maxFileSize) {
        super();
        this.context = context;
        this.maxCacheSize = maxCacheSize;
        this.maxFileSize = maxFileSize;
        String userAgent = Util.getUserAgent(context, context.getString(R.string.app_name));
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        defaultDatasourceFactory = new DefaultDataSourceFactory(this.context,
                bandwidthMeter,
                new DefaultHttpDataSourceFactory(userAgent, bandwidthMeter));
    }

    @Override
    public DataSource createDataSource() {
        LeastRecentlyUsedCacheEvictor evictor = new LeastRecentlyUsedCacheEvictor(maxCacheSize);
        SimpleCache simpleCache = new SimpleCache(new File(context.getCacheDir(), "media"), evictor);
        return new CacheDataSource(simpleCache, defaultDatasourceFactory.createDataSource(),
                new FileDataSource(), new CacheDataSink(simpleCache, maxFileSize),
                CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null);
    }
}

还有玩家

BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
        new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

SimpleExoPlayer exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
MediaSource audioSource = new ExtractorMediaSource(Uri.parse(url),
            new CacheDataSourceFactory(context, 100 * 1024 * 1024, 5 * 1024 * 1024), new DefaultExtractorsFactory(), null, null);
exoPlayer.setPlayWhenReady(true); 
exoPlayer.prepare(audioSource);

效果很好。

关于android - 在 ExoPlayer 中使用缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28700391/

相关文章:

android - RelativeLayout 支持多种屏幕尺寸

android - 不同设备上不同大小的 ImageView

java - 如何每 X 分钟清除一次应用程序缓存?

android - 从相机拍摄的图像中获取图像

jquery - popcorn.js 开始和停止时间

java - 改变 Activity 时如何平稳过渡

Android - 如何直接转到返回堆栈中的上一个 Activity 并忽略 fragment 返回堆栈或当前 Activity 中的剩余 fragment ?

android - 在 Travis CI 中缓存 Android SDK

android - Glide 在内存中缓存离屏图像

html - 回复 CSS Not Working Properly