DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 13.9 Queuing Sounds

13.9.1 Problem

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

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

13.9.3 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(  );

13.9.4 See Also

Recipe 13.6 and Recipe 13.8

    [ Team LiB ] Previous Section Next Section