android - exoplayer 中的 CacheDataSource 与 SimpleCache?

标签 android exoplayer2.x

我对 ExoPlayer 及其文档感到很困惑。请解释一下我们应该使用 CacheDataSource 的目的是什么,什么时候使用 SimpleCache?

最佳答案

CacheDataSourceSimpleCache 实现两个不同的目的。如果您查看他们的类原型(prototype),您会发现 CacheDataSource 实现了 DataSource 并且 SimpleCache 实现了 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);

然后使用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);

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

Only one instance of SimpleCache is allowed for a given directory at a given time

根据 documentation .因此,为了对文件夹使用 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)));
    }
}

TL;博士

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

关于android - exoplayer 中的 CacheDataSource 与 SimpleCache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63883690/

相关文章:

java - ExoPlayer 设置命令找不到 UNKNOWN_TIME

android - Exoplayer - 如何检查 MP4 视频是否有音频?

java - Exoplayer 离线 - 下载消耗的数据量超过文件大小

java - 当我尝试通过拖放运行 Android 应用程序时出现意外错误

android - 显式 Intent 广播接收器 - Action 过滤器行为

android - "Failed to find provider info for android.server.checkin"是什么意思?

android - 如何修复此 PlayerNotificationManager.createWithNotificationChannel 错误

android - 在 ExoPlayer 中,如何使用 SimpleExoPlayer.setVideoScalingMode 就像在 ImageView center-crop 中一样?

android - 在lua中旋转一个物理对象

java - 为什么Android AudioRecord 初始化失败?