Skip to content

Instantly share code, notes, and snippets.

@VladSumtsov
Created November 2, 2016 09:20
Show Gist options
  • Save VladSumtsov/11a8e023e89dab44e3840f62cfb169a5 to your computer and use it in GitHub Desktop.
Save VladSumtsov/11a8e023e89dab44e3840f62cfb169a5 to your computer and use it in GitHub Desktop.
helper for playing sounds
package com.grasshopper.dialer.util;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.annotation.RawRes;
import java.util.HashMap;
import java.util.Map;
import rx.functions.Action1;
public class SoundPoolHelper extends SoundPool {
private float volume;
private Map<Integer, Integer> loaded;
private Map<Integer, Integer> tempLoaded;
private Context mContext;
public SoundPoolHelper(int maxStreams, Context context) {
this(maxStreams, AudioManager.STREAM_MUSIC, 0, context);
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume / maxVolume;
}
private SoundPoolHelper(int maxStreams, int streamType, int srcQuality, Context context) {
super(maxStreams, streamType, srcQuality);
mContext = context;
loaded = new HashMap<>();
tempLoaded = new HashMap<>();
setOnLoadCompleteListener((soundPool, sampleId, status) -> {
int resId = tempLoaded.get(sampleId);
tempLoaded.remove(sampleId);
if (status == 0) {
loaded.put(resId, sampleId);
}
});
}
@Override public int load(Context context, int resId, int priority) {
int id = super.load(context, resId, priority);
tempLoaded.put(id, resId);
return id;
}
public void play(@RawRes int res) {
if (loaded.containsKey(res)) {
play(loaded.get(res), volume, volume, 0, 0, 1.0f);
} else {
throw new IllegalAccessError("Load this raw resource previously.");
}
}
public Action1<Integer> asAction() {
return this::play;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment