Looping multiple songs in flashpunk

Hello!  Today I’m going to talk about looping multiple songs in flashpunk.  If you just want to loop one song, you can simply call:

soundeffect.loop();

But if you want multiple songs located in separate files to loop, then it gets harder.  I use the following code:

[Embed(source = '../assets/music/song1.mp3')] private const BGMusicEmbed1:Class;
public var BGMusic1:Sfx = new Sfx(BGMusicEmbed1);
[Embed(source = '../assets/music/song2.mp3')] private const BGMusicEmbed2:Class;
public var BGMusic2:Sfx = new Sfx(BGMusicEmbed2);

public var tracks:Array = new Array(BGMusic1, BGMusic2);
public var musicplaying:Boolean = false;
//...
//...

//Inside update loop:
musicplaying = false;

for (var i:Number = 0; i < tracks.length; i ++)
{
    if (tracks[i].playing)
    {
        musicplaying = true;
    }
}

if (!musicplaying)
{
    tracks[FP.rand(tracks.length)].play()
}

Now I’ll explain what that does.

The first 5 lines embed 2 songs and put them in a array.

The first for loop finds out if any of the songs are playing.  If none are playing, it sets musicplaying to false.

The if statement plays a random song from the array if no songs are playing at the moment.

There are a number of ways this could be improved.  It could keep track of the song it was last playing and make sure not to play it twice in a row.  It could also loop through them, shuffling the array each time, so that it will have the maximum amount of time between each song repeating while still playing a random song.  This snippet is just a *simple* song manager.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s