Playing local R.raw files with ExoPlayer2

ExoPlayer is looking like the saviour of Android media players.

Briefly what lead me to ExoPlayer:

I need to seamlessly loop audio in my app, and Android sucks at this. SoundPool works with small files, but then that was broken for a while ~Android 4.3. This lead me to use MediaPlayer and the setNextMediaPlayer method, this worked well for quite a while. But now it has very small gaps on Samsung devices Android 6+ (thanks Samsung).

So.. ExoPlayer to the rescue? Yes, but with it comes a pretty convoluted API. Here is how I looped an OGG file from R.raw (there may be better ways, but I couldn’t find anything):

SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector(new Handler()), new DefaultLoadControl());

DataSpec dataSpec = new DataSpec(RawResourceDataSource.buildRawResourceUri(R.raw.rain));
final RawResourceDataSource rawResourceDataSource = new RawResourceDataSource(context);;

DataSource.Factory factory = new DataSource.Factory() {
public DataSource createDataSource() {
return rawResourceDataSource;

MediaSource audioSource = new ExtractorMediaSource(rawResourceDataSource.getUri(),
factory, OggExtractor.FACTORY, null, null);
LoopingMediaSource loopingMediaSource = new LoopingMediaSource(audioSource);