Sunday, 8 September 2013

Android SoundPool load() returning null

Android SoundPool load() returning null

I'm working on an Android app and trying to use SoundPool to play some
music in the background (I know MediaPlayer would be better for this, but
I really want to figure out how to use this class since it's frustrating
me). I'm trying to load two mp3 files using a static Music class and store
their sound IDs in a HashMap so I can access them when they're ready to be
used. However, putting them in a HashMap is giving me a
NullPointerException.
public static void play(Context context, int resource) {
if (sp == null) {
sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
sp.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
sounds.put(R.raw.main, sp.load(context, R.raw.main, 1));
sounds.put(R.raw.game, sp.load(context, R.raw.game, 1));
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
float volume = am.getStreamVolume(AudioManager.STREAM_MUSIC) /
am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
sp.play(sounds.get(resource), volume, volume, 0, -1, 1.0f);
} else {
float volume = am.getStreamVolume(AudioManager.STREAM_MUSIC) /
am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
sp.play(sounds.get(resource), volume, volume, 0, -1, 1.0f);
}
}
Specifically, I'm getting an NullPointerException on the line
sounds.put(R.raw.main, sp.load(context, R.raw.main, 1));
I've tried using a while loop immediately after loading the sound files
that simply loops until "loaded" is true, but that just results in the app
hanging forever. Any help would be greatly appreciated.

No comments:

Post a Comment