Recipe 15.1.
Creating a Sound Object and Loading a Sound
Problem
You
want to load into your
.swf and have it available to the application.
Solution
Create a Sound object and load an external
sound file into it.
Discussion
Creating a Sound object is as easy as
making an instance of any class. First, though, make sure the
Sound class is imported:
import flash.media.Sound;
and then just create an instance of the
Sound class:
_sound = new Sound( );
Now of course, you need to give it a sound file
to play. As mentioned earlier, this will be an external MP3 file,
such as a song. For all of the examples in this chapter, it's
assumed that you have an MP3 file named song.mp3, and that
this is stored in the same directory as the .swf on your
server or hard drive.
To load a sound file into your Sound
object, first create a URLRequest object (you'll need to
import flash.net.URLRequest), passing in the string
containing the path to the MP3 file:
soundFile = new URLRequest("song.mp3");
You can then pass this to the load method of
your Sound object:
_sound.load(soundFile);
You can even shortcut these last two steps, as
seen in the following class example:
package {
import flash.display.Sprite;
import flash.media.Sound;
import flash.net.URLRequest;
public class LoadSoundExample extends Sprite {
private var _sound:Sound;
public function LoadSoundExample ( ) {
_sound = new Sound( );
_sound.load(new URLRequest("song.mp3"));
}
}
}
The class now has a property, _sound,
which you can use any time you need to play that sound. Note that
the sound does not actually start playing yet. You have merely set
it up and started the sound information coming in. See Recipe
15.2 for information on how to control a sound's playing.
An even quicker way is to pass the
URLRequest right into the constructor when you create the
sound, like so:
public function LoadSoundExample( ) {
_sound = new Sound(new URLRequest("song.mp3"));
}
When you pass in the request in the constructor
like this, the sound automatically calls its own load( )
method right away and starts to load that sound data. This is
especially useful if you are only loading a single sound file into
the Sound object.
Otherwise, it may be better to create the
Sound object beforehand and call the load( ) method
when you know which sound file you want to load. An example of this
is a music player application in which users can select a song from
a play list. When the song is selected, the application sends its
path to the sound's load( ) method, and it is ready to
play.
|