Music Looping in AS3
According to the AS3 documentation you can loop a sound by passing in a loop number argument when you call play on a sound. Apparently, that never seems to work consistently for me. Sometimes it would not loop after a number of times, or it doesn’t loop immediately. So I usually just manually control the looping of music with Event Listeners.
To do this, I add an Event Listener to the music channel that will call a function to replay the sound whenever it’s done playing once.
public function playMusic():void
{
musicChannel = music.play();
musicChannel.addEventListener(Event.SOUND_COMPLETE, loopMusic);
}
public function loopMusic(e:Event):void
{
if (musicChannel != null)
{
musicChannel.removeEventListener(Event.SOUND_COMPLETE, loopBackgroundMusic);
playMusic();
}
}
So the sound will continue to loop forever until I stop it. Whenever I do, I have to remove the Event Listener from the music channel or else it won’t be garbage collected.
public static function stopMusic():void
{
if (musicChannel != null)
{
musicChannel.stop();
musicChannel.removeEventListener(Event.SOUND_COMPLETE, loopMusic);
}
}
That’s about it. A pretty simple solution to an annoying problem sometimes.
Tags: actionscript 3, programming



February 25th, 2008 at 5:35 pm
cool thanks, although i think:
musicChannel.removeEventListener(Event.SOUND_COMPLETE, loopBackgroundMusic);
should be:
musicChannel.removeEventListener(Event.SOUND_COMPLETE, loopMusic);
May 8th, 2008 at 7:24 am
i’m sry, but wat is that musicChannel != null checking?
June 24th, 2008 at 5:50 am
[...] or twice. Again I went around reading on codes.. And found I wasn’t alone. Then I came across a simpler workaround using functions call, better than the former [...]
June 24th, 2008 at 11:11 am
I’ve used the the same methods as thise described above several times. A simpler way to achieve the same thing is to use the following:
musicChannel = music.play(0, int.MAX_VALUE);
This basically takes the maxium integer value available in AS3 as the second param. It should be sufficient enough for most use cases.
August 10th, 2008 at 2:15 am
Thanks man, i’ve been searchin for something like this simple musicChannel = music.play(0, int.MAX_VALUE);
October 17th, 2008 at 4:27 am
I think you can get around having to remove the listeners every time by using weak references, detailed here:
http://www.gskinner.com/blog/archives/2006/07/as3_weakly_refe.html
I’ve not tried it, but it sounds like what you’re after - weak references don’t stop something being garbage collected.
Loved Zunderfury, by the way!
November 12th, 2008 at 7:28 pm
ggygggggggggggggggggggggg
November 12th, 2008 at 7:29 pm
dfdfdfdfdfdfdfdfd
November 12th, 2008 at 7:30 pm
i hate it