13.9. Queuing Sounds

Problem

You want to play multiple sounds in series (one after another).

Solution

Create an array of Sound objects and use an onSoundComplete( ) method to play the next sound in the array when the preceding sound ends.

Discussion

You can queue sounds rather easily by using an onSoundComplete( ) method to start the next sound when the preceding one finishes. The most convenient way to keep track of the order of sounds is to place the Sound objects in an array.

The following example creates a queue of three sounds (all songs judging by the names), which play one after another:

// Create an array of Sound objects. This example assume that the Sound objects
// already exist.
_global.soundQueue_array = new Array(song0_sound, song1_sound, song2_sound);

// Use a custom property to track the current sound 
// element index. Initialize it to 0.
_global.soundQueue_array.currentIndex = 0;

// Define the function that we assign to the onSoundComplete(  ) method for each of the
// Sound objects. This function starts the next sound in the array.
function startNextInQueue (  ) {
  _global.soundQueue_array[++_global.soundQueue_array.currentIndex].start(  );
}

// Assign the startNextInQueue(  ) function as the onSoundComplete(  ) handler for each // of the elements of the array. for (var i = 0; i < soundQueue_array.length; i++) { startNextInQueue[i].onSoundComplete = startNextInQueue; } // Start the first sound. The remaining sounds play after it finishes. _global.soundQueue_array[0].start( ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.