Playing local R.raw files with ExoPlayer2

Tony Owen
1 min readOct 15, 2016

--

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);
rawResourceDataSource.open(dataSpec);

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

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

player.prepare(loopingMediaSource);
player.setPlayWhenReady(true);

--

--

Tony Owen
Tony Owen

Written by Tony Owen

Flutter Fan Boy & Android Developer

Responses (10)