首页 > 解决方案 > 缓存的视频不能立即播放?

问题描述

我将 HLS 视频与 ExoPlayer 一起使用。每个片段被分解为 6 ​​秒。

我的应用程序有一个视频源(在 a 中RecyclerView)。我已将其设置为,当视频停止时,它会将位置保存在地图中,并且播放器会分离。但是,如果用户向上滚动以查看相同的视频,当我调用 时exoPlayer.seekTo(position),即使视频应该被缓存,视频通常也需要一两秒钟才能从保存的位置重新开始播放。

我究竟做错了什么?缓存不适用于 HLS 视频还是我的实现有误?

缓存单例类:

public class VideoCache {

    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));
    }

}

媒体源工厂类:

public class CustomMediaSourceFactory {

    public static DataSource.Factory buildMediaSourceFactory(Context context) {
        OkHttpDataSource.Factory okHttpDataSourceFactory = new OkHttpDataSource.Factory(UnsafeOkHttpClient.getUnsafeOkHttpClient().build());

        DataSource.Factory cacheDataSourceFactory =
                new CacheDataSource.Factory()
                        .setCache(VideoCache.getInstance(context))
                        .setUpstreamDataSourceFactory(okHttpDataSourceFactory);

        return cacheDataSourceFactory;
    }

}

我像这样使用它:

this.hlsMediaSourceFactory = new HlsMediaSource.Factory(CustomMediaSourceFactory.buildMediaSourceFactory(context))
                .setAllowChunklessPreparation(true);
this.exoPlayer = new SimpleExoPlayer.Builder(context)
                .setMediaSourceFactory(this.hlsMediaSourceFactory)
                .build();

稍后在代码中,我使用:

exoPlayer.setMediaSource(hlsMediaSourceFactory.createMediaSource(MediaItem.fromUri(video.getUrl())));

任何帮助表示赞赏!

标签: androidexoplayerexoplayer2.xandroid-video-player

解决方案


推荐阅读