• ExoPlayer + 边缓存边播放


    在此基础上改动: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

  • 相关阅读:
    html调用php
    MySQL安装下载
    MySQL默认安装下载
    MySQL安装下载
    搭建php环境
    面试官:聊聊对Vue.js框架的理解
    TCP、UDP、HTTP、SOCKET之间的区别与联系
    HTTP/1、HTTP/2、HTTP/3
    git教程
    从jQuery到Serverless,前端十四年挖了多少坑?
  • 原文地址:https://www.cnblogs.com/candyzhmm/p/11457401.html
Copyright © 2020-2023  润新知