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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM