dndr
dndr

Reputation: 2359

Flash SoundChannel limit and memory management

I have a program that I use as a recording platform, and for each sound I play I make a new Sound.

        public function playAudioFile():void {
            trace("audio file:", currentAudioFile);
            sound = new Sound();
            sound.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); 
            sound.addEventListener(Event.COMPLETE, soundLoaded);
            sound.load(new URLRequest(soundLocation + currentAudioFile));
        }

        public function soundLoaded(event:Event):void {
            sound.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler); 
            sound.removeEventListener(Event.COMPLETE, soundLoaded);
            var soundChannel:SoundChannel = new SoundChannel();
            soundChannel = sound.play();
            soundChannel.addEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
            trace('soundChannel?', soundChannel);
        }

        public function handleSoundComplete(event:Event):void {
            var soundChannel:SoundChannel = event.target as SoundChannel;
            soundChannel.stop();
            soundChannel.removeEventListener(Event.SOUND_COMPLETE,handleSoundComplete);
            soundChannel = null;
        }

After 32 times, I stop getting a SoundChannel object when I call sound.play() (in soundLoaded). However, I don't need to have 32 SoundChannel objects because I play these sounds only serially and not at the same time. How can I get rid of the SoundChannel after I 'used' it to play a file?

Upvotes: 0

Views: 542

Answers (1)

prototypical
prototypical

Reputation: 6751

You could be explicit about the soundChannel you use :

var soundChannel:SoundChannel = new SoundChannel();
soundChannel = sound.play();
soundChannel.addEventListener(Event.SOUND_COMPLETE,handleSoundComplete);

Then when you are done playing the sound, you can then set the channel to null so it will be marked for garbage collection :

function handleSoundComplete(e:Event):void
{
   var soundChannel:SoundChannel = e.target as SoundChannel;
   soundChannel.removeEventListener(Event.SOUND_COMPLETE,handleSoundComplete);
   soundChannel = null;
}

Keep in mind that you need to remove those event listeners that you show in your code above, when the sound is done loading.

Also keep in mind that when you set something to null, that just sets it as fair game for garbage collection, it doesn't force garbage collection.

Another note is that this code I have posted is just an example, and you might want to think about having several sound channels instances that you keep active, and reuse as needed. Management is required in that case, but then you will not be constantly creating/killing sound channels.

Upvotes: 2

Related Questions