So I found a simple song manager, how to improve it?


(John Andersson) #1

I googled and found this:

Now at the end, the article states “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.

Any ideas on how to do this?


(Zachary Lewis) #2

Here’s a simple example of creating a random playlist that loops forever without any repeating any songs and having all songs be played with the same frequency.

/** The list of songs to play. */
var songList:Vector.<Sfx> = new Vector.<Sfx>();

// Populate songList with the songs you want to play.

/** The song currently playing. */
var currentSongIndex:uint = 0;

/**
 * The last song played.
 * Used to make sure a song isn't played twice in a row.
 */
var lastSong:Sfx;

override public function update():void
{
  // Has the current song stopped?
  if (!songList[currentSong].playing)
  {
    // Next song.
    currentSongIndex++;

    // Are there any songs left?
    if (currentSongIndex >= songList.length)
    {
      // Remember the last song played.
      lastSong = songList[songList.length];

      // Randomize the song list until the first song isn't
      // the last song played.
      // (Also error check to prevent an infinite loop.)
      do
      {
        FP.shuffle(songList);
      } while (songList[0] != lastSong && songList.length > 1);

      // Restart playlist at the first song.
      currentSongIndex = 0;
    } 

    // Begin playing the next song.
    songList[currentSongIndex].play();
  }

  super.update();
}