I'm looking for any example of implementing cache in ExoPlayer.
ExoPlayer has in its library different classes concerning cache and Google explain in this video that we can implement it with the CacheDataSource class, but Google doesn't provide any demo on it. Unfortunately this seems pretty complicated to use, so I'm currently looking for examples (no success on Google).
Does anyone succeed or has any info that would help ? Thanks.
Here is an example which replaces demo data source with OkHttp, default is no cache https://github.com/b95505017/ExoPlayer/commit/ebfdda8e7848a2e2e275f5c0525f614b56ef43a6 https://github.com/b95505017/ExoPlayer/tree/okhttp_http_data_source So, you just need to configure OkHttp cache properly and requests should be cached.
In addition to Bao Le's answer, here's ready to use Kotlin version of
CacheDataSourceFactory
that keeps one instance ofSimpleCache
to solve the problem of multiple Cache objects writing to the same directory.Here is the solution for ExoPlayer 2.+
Create a custom cache data source factory
And the player
It works pretty well.
Exoplayer's documentation list's the class DashDownloader and has some example code for that type of source. (Click [Frames] to get back navigation of the documentation. I had to remove it to get the deep link.)
By default ExoPlayer do not cache media (video, audio, etc...). For example if you want to play an online video file, each time ExoPlayer will open a connection, read data then play it.
Fortunately, it provides us some interfaces and implementation classes to support caching media in our app.
You can write your own cache which implement given interfaces from ExoPlayer. To make it simple I will guide you how to enable cache by using implementation classes.
Step 1: Specify a folder which contains your media files, in Android for smaller cache folder (less than 1MB), you should use getCacheDir, otherwise you can specify your prefer cache folder, getFileDir for example.
Step 2: Specify a size for the cache folder, and policies when the size is reached out. There are 2 APIs
Put it together
Here's my sample in Kotlin (project available here) :