Skip to content

Instantly share code, notes, and snippets.

@kwong93
Created August 6, 2017 16:23
Show Gist options
  • Save kwong93/717bffc3c63d408840a8fae43c9c8b50 to your computer and use it in GitHub Desktop.
Save kwong93/717bffc3c63d408840a8fae43c9c8b50 to your computer and use it in GitHub Desktop.
How to cache mp3 files using ExoPlayer
private final ExoPlayer exoPlayer;
public PlayerExoPlayer(ExoPlayer exoPlayer) {
this.exoPlayer = exoPlayer;
}
public void prepareMp3(Context context, Uri uri) {
DefaultBandwidthMeter defaultBandwidthMeter = new DefaultBandwidthMeter();
String userAgent = System.getProperty("http.agent");
DataSource.Factory dataSourceFactory = new DefaultHttpDataSourceFactory(userAgent, defaultBandwidthMeter);
int cacheSizeInBytes = 100 * 1024 * 1024;
LeastRecentlyUsedCacheEvictor leastRecentlyUsedCacheEvictor = new LeastRecentlyUsedCacheEvictor(cacheSizeInBytes);
File cacheDirectory = new File(context.getCacheDir(), "exoplayer_mp3_cache");
SimpleCache simpleCache = new SimpleCache(cacheDirectory, leastRecentlyUsedCacheEvictor);
int maxCacheFileSize = 4 * 1024 * 1024;
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(simpleCache, dataSourceFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, maxCacheFileSize);
MediaSource mediaSource = new ExtractorMediaSource(uri, cacheDataSourceFactory, new DefaultExtractorsFactory(), null, null);
exoPlayer.prepare(mediaSource);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment