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

6 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. music says:

    music…

    There was a time I get it, so I couldn’t say it’s too bad. It’s pretty nice….

  3. Ruth says:

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

  4. … @ 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 [...]

  5. 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.

  6. ZennMaster says:

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

Leave a Reply