ExoPlayer + 边缓存边播放

2019/09/04 10:22
阅读数 451

在此基础上改动:https://www.cnblogs.com/candyzhmm/p/9957928.html

private void openPlayer(String videoUrl) {
//创建播放器
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);

//创建加载数据的工厂
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
Util.getUserAgent(this, BuildConfig.APPLICATION_ID), (TransferListener<? super DataSource>) bandwidthMeter);

CacheDataSourceFactory videoDataSourceFactory = null;
Cache cache = VideoCache.getInstance();
long dataSize = FileUtils.getDirLength(CACHE_VIDEO_PATH);
if (dataSize < Constants.CACHE_VIDEO_SIZE) {
// CacheDataSinkFactory 第二个参数为单个缓存文件大小,如果需要缓存的文件大小超过此限制,则会分片缓存,不影响播放
DataSink.Factory cacheWriteDataSinkFactory = new CacheDataSinkFactory(cache, Long.MAX_VALUE);
videoDataSourceFactory = new CacheDataSourceFactory(cache, dataSourceFactory, new FileDataSourceFactory(), cacheWriteDataSinkFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null);
}

Uri videoUri = null;
try {
videoUri = Uri.parse(videoUrl);
} catch (Exception e) {
return;
}
MediaSource videoSource = null;
if (videoDataSourceFactory == null) {
videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(videoUri);
} else {
videoSource = new ExtractorMediaSource.Factory(videoDataSourceFactory).createMediaSource(videoUri);
}
//循环播放
LoopingMediaSource loopingMediaSource = new LoopingMediaSource(videoSource);
player.prepare(loopingMediaSource);
player.addListener(eventListener);
player.setPlayWhenReady(true);
}

public class VideoCache {

    private static SimpleCache sDownloadCache;

    public static SimpleCache getInstance() {
        if (sDownloadCache == null)
            sDownloadCache = new SimpleCache(createFile(Constants.CACHE_VIDEO_PATH), new NoOpCacheEvictor());
        return sDownloadCache;
    }

    private static File createFile(String path) {
        File file = new File(path);
        //判断文件目录是否存在
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }
}

还有另外一种实现视频缓存方式:

AndroidVideoCache  参考:https://www.jianshu.com/p/53c4a6c9bd07

github地址: https://github.com/danikula/AndroidVideoCache

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部