Exoplayer2学习--LoadControl,CacheDataSourceFactory 实现本地缓存和预加载控制

这篇文章记录一下如何通过LoadControl来控制exoplayer2默认的预加载机制

可以通过CacheDataSourceFactory来实现本地缓存的功能. 凡是下载的数据会在设定的缓存目录中保存下来, 如下是一个示例:

DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(VUtil.getApplication(),
            Util.getUserAgent(VUtil.getApplication(), VUtil.getApplication().getString(R.string.app_name)));

 File cacheFile = new File(VUtil.getApplication().getExternalCacheDir().getAbsolutePath(), "video");
    VLog.d(TAG, "PlayerWrapper()  cache file:" + cacheFile.getAbsolutePath());
  SimpleCache simpleCache = new SimpleCache(cacheFile, new LeastRecentlyUsedCacheEvictor(512 * 1024 *     1024)); // 本地最多保存512M, 按照LRU原则删除老数据
CacheDataSourceFactory cachedDataSourceFactory = new CacheDataSourceFactory(simpleCache,    dataSourceFactory);

手机数据业务下的预加载控制

自定义一个LoadControl对象 , LdDefaultLoadControl
具体实现可以参考Exoplayer2中附带的实现om.google.android.exoplayer2.DefaultLoadControl
唯一要修改的地方是:

public boolean shouldContinueLoading(long bufferedDurationUs)

自定义的具体实现:

@Override
public boolean shouldContinueLoading(long bufferedDurationUs) {
   if (!VUtil.isWifiConnected(VUtil.getApplication())) {//如果没有wifi连接则判断是否是用户主动播放
        if(!userAction){
            return false;  // 如果不是用户主动点击播放, 那就是预加载了, 那么返回, 不再预加载
        }
    }
    int bufferTimeState = getBufferTimeState(bufferedDurationUs);
    boolean targetBufferSizeReached = allocator.getTotalBytesAllocated() >= targetBufferSize;

    boolean wasBuffering = isBuffering;
    isBuffering = bufferTimeState == BELOW_LOW_WATERMARK
            || (bufferTimeState == BETWEEN_WATERMARKS && isBuffering && !targetBufferSizeReached);
    if (priorityTaskManager != null && isBuffering != wasBuffering) {
        if (isBuffering) {
            priorityTaskManager.add(C.PRIORITY_PLAYBACK);
        } else {
            priorityTaskManager.remove(C.PRIORITY_PLAYBACK);
        }
    }
    return isBuffering;
}

另外对于参数userAction的定义:

// 用来记录当前的播放动作是否是用户主动事件, 因为在数据业务模式下需要用户同意才能播放视频
// 这个值在外围生成LdDefaultLoadControl对象时作为参数传进来
private boolean userAction;

/**
 * Constructs a new instance, using the {@code DEFAULT_*} constants defined in this class.
 */
public LdDefaultLoadControl(boolean userAction) {
    this(new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE));
    this.userAction = userAction;
}

代码

你可能感兴趣的:(Exoplayer2学习--LoadControl,CacheDataSourceFactory 实现本地缓存和预加载控制)