The documentation of this library is so bad. It took me hours to write a simple functionality. If anyone is interested, this code works:
public static void playSound(Context context, int sounRes, float volume)
{
//example int sounRes=R.raw.duck;
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);
DataSpec dataSpec = new DataSpec(RawResourceDataSource.buildRawResourceUri(sounRes));
final RawResourceDataSource rawResourceDataSource = new RawResourceDataSource(context);
try {
rawResourceDataSource.open(dataSpec);
} catch (RawResourceDataSource.RawResourceDataSourceException e) {
e.printStackTrace();
}
DataSource.Factory factory = () -> rawResourceDataSource;
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource
.Factory(factory)
.createMediaSource(rawResourceDataSource.getUri());
player.prepare(mediaSource);
player.setPlayWhenReady(true);
player.setVolume(volume);
player.addListener(new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_ENDED) {
player.release();
}
}
});
}
If you want to use an asset file, then use this:
public static void playSound(Context context,String audioPath,float volume)
{
//example String audioPath = "duck.mp3";
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "exoPlayerSample"));
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource
.Factory(dataSourceFactory)
.createMediaSource(Uri.parse("asset:///" + audioPath));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
player.setVolume(volume);
player.addListener(new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if(playbackState == Player.STATE_ENDED){
player.release();
}
}
});
}