15.5. Loading an External MP3 Sound

Problem

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

Solution

Use the Sound.loadSound( ) method.

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 Sound.as file from Chapter 13.
#include "Sound.as"
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 ...

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.