'How to stop all sounds in SoundPool?

I am using SoundPool to play sfx sounds in a game on Android. In most cases it works perfectly, except sometimes I need to stop all sounds at once not pause (doesn't matter if they are set to loop or not). I can't figure out how to stop a sound from playing without knowing the StreamID of that sound. What I know:

  • soundpool.load(...some sound...) returns a soundID
  • soundpool.play(soundID) plays the sound and returns a streamID
  • soundpool.stop(streamID) stops the sound

My question is, how can I stop a sound without knowing the streamID ? I tried tracking all streamIDs in a list, but sometimes there are so many short streams playing at once, that it won't work. And I can't find any method in SoundPoolto get the active streamIDs. Does anyone know how to stop all sounds? Any hint is appreciated! thanks



Solution 1:[1]

I'd recommend using autoPause() and autoResume() to pause and restart your sounds. This function is part of the soundpool:

http://developer.android.com/reference/android/media/SoundPool.html#autoPause()

Solution 2:[2]

What about using .release() ? Accourding to the documentation:

Release the SoundPool resources. Release all memory and native resources used by the SoundPool object. The SoundPool can no longer be used and the reference should be set to null.

I think it also stops everything. (Actually it was causing a bug at one of my apps, that's why I say it)

However, I believe that if you want to play any sounds later, you may have to load them again.

Solution 3:[3]

SoundPool doesn't have a method to retrieve the streamID from the index of the stream, like it should. So even when you know the maximum number of streams, you can't just iterate through like the following:

for(int index=0;index<MAXSTREAMS;index++){
 int streamid = SoundPool.getStreamID(index);//getStreamID action doesn't exist :(
 soundpool.stop(streamid);
}

As you mentioned, the coder has to manage this himself with a list. I implement the declaration as follows:

List<Integer> streams = new ArrayList<Integer>();

You can add and remove soundIDs to this list as you play and stop sounds as follows:

streams.add(batattack_soundID);
streams.remove(Integer.valueOf(batattack_soundID));//NOT streams.remove(batattack_soundID);

Be sure to use Integer.valueOf() or .remove() will interpret your parameter as an index position, likely giving you an IndexOutOfBoundsException.

To clean everything up you can code as follows:

for (Integer stream : streams) {
   soundPool.stop(stream);
}
streams.clear();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shygar
Solution 2 anestv
Solution 3