32 SoundChannels Limit

Im currently working on a small physics game involving a lot of sound fx  when collision occur. Object bouncing against walls, each other and so on.
I ran into the issue that more that 32 active SoundChannels are not supported by Flash/AIR.  I was having lots of bounce sound fx playing and then the player would die, but no sound appear because the 32 limit was occupied by all the bounce fx.

I came of with a very simple solution for this:

When playing a sound, add reference to SoundChannel in a list. When Sound completes, remove from list. If the SoundChannel of the sound you want to play is null, meaning we reached the 32 limit, then remove the “oldest” SoundChannel from the list to give room for the sound you want to play.

And it work, and you really can’t tell any difference.


// Store active SoundChannels
private var _activeChannels:Array = [];

private function play(soundName:String, volume:Number = 1, pan:Number = 0):void
{
    // Get sound from Starlings AssetManager.
    var s:Sound = _assets.getSound(soundName);
    var sc:SoundChannel = s.play(0,0,new SoundTransform(volume, pan));
    // 32 Limit reached, remove the oldest one.
    if(sc == null)
    {
        // Take the first sound and remove it.
        disposeSoundChannel(_activeChannels[0] as SoundChannel);
        sc = s.play();
    }
    _activeChannels.push(sc);
    sc.addEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
}

private function handleSoundComplete(event:Event):void
{
    var sc:SoundChannel = event.currentTarget as SoundChannel;
    disposeSoundChannel(sc);
}

private function disposeSoundChannel(sc:SoundChannel):void
{
    sc.removeEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
    sc.stop();
    var i:int = _activeChannels.indexOf(sc);
    _activeChannels.splice(i,1);
    sc = null;
}