Recipe 15.5 Loading an External MP3 Sound

15.5.1 Problem

You want to load an MP3 sound file into your Flash movie at runtime.

15.5.2 Solution

Use the Sound.loadSound( ) method.

15.5.3 Discussion

You can use the Sound.loadSound( ) method to load MP3 sound files into your Flash movie at runtime. The first step is to create a Sound object. For this purpose, use the custom createNewSound( ) method from Recipe 13.1:

// Include the file from Chapter 13.
#include ""
mySound = Sound.createNewSound(  );

Next, call the loadSound( ) method from the Sound object. You should pass the loadSound( ) method two parameters: the URL where the MP3 can be found and a Boolean value indicating whether the sound should be streamed. Be careful to select the correct option for streaming because there is a major difference between streamed and nonstreamed sounds. Streaming sounds begin playing automatically as soon as enough data has been buffered (i.e., enough of the sound has loaded into the Flash movie). Nonstreamed sounds, on the other hand, must load completely into the movie before you can instruct them to start playing. You can control a nonstreamed sound using all the methods and properties of a Sound object. Streaming sounds, however, cannot be controlled other than by stopping the playback:

// Load an MP3 from the same directory as the Flash movie. Set streaming to false.
mySound.loadSound("myMP3.mp3", false);

You cannot start the playback of a nonstreamed sound until it has loaded completely, nor can you retrieve any information about the sound (duration, position, etc.) until after the loading is finalized. Therefore, you should monitor the loading of a sound and define a callback function to be called once loading is complete. You can use the same techniques to monitor the loading of an MP3 that you use to monitor the loading of a JPEG or SWF. See Recipe 15.7 and Recipe 15.8 for more information on these techniques.

15.5.4 See Also

Recipe 2.7, Recipe 13.2, and Recipe 14.5

    Part I: Local Recipes
    Part II: Remote Recipes