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: ,

9 Responses to “Music Looping in AS3”

  1. Jadon says:

    cool thanks, although i think:

    musicChannel.removeEventListener(Event.SOUND_COMPLETE, loopBackgroundMusic);

    should be:

    musicChannel.removeEventListener(Event.SOUND_COMPLETE, loopMusic);

  2. Ruth says:

    i’m sry, but wat is that musicChannel != null checking?

  3. … @ a distance … » Actionscript says:

    [...] 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 [...]

  4. David B says:

    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.

  5. ZennMaster says:

    Thanks man, i’ve been searchin for something like this simple musicChannel = music.play(0, int.MAX_VALUE);

  6. Tom says:

    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!

  7. u says:

    ggygggggggggggggggggggggg

  8. u says:

    dfdfdfdfdfdfdfdfd

  9. u says:

    i hate it

Leave a Reply