Monday, July 26, 2010

Sound class in Actionscript 3: Part 1

Sounds have an important role in all kinds of flash applications. Today we will learn how to play and manage sound in Actionscript 3.

First we need to create a new sound example:

var mysound = new Sound();

Now we need to tell the flash the path to our mp3 file (flash can only load external sound files with .mp3 format, and we assume it is located in the same folder as our .swf):

var soundUrl = new URLRequest("mysong.mp3");

After that, we have to pass the object to Sound load method:

mysound.load(soundUrl);

We can combine the last 2 steps together:

mysound.load(new URLRequest("mysong.mp3"));

Or combine all 3 steps into one line:

mysound = new Sound(new URLRequest("mysong.mp3"));

We loaded the sound file into our flash, but we didn't play it yet! This is probably the hardest step:

mysound.play();

You can set the sound's starting position in milliseconds and set how many times you want it to repeat:

mysound.play(1000, 3);

You can stop a sound using the stop() method.
Close() method not only stops the sound from playing, but also from loading. After 'closing' a sound, you'll need to load() it again to play it.

Now we know how to load external audio files. How do we load audio files from our library?

First of all, import a sound file you like (library supports not only .mp3 audio format, but also .wav) then go to its properties and set its class name to "mysong". Now, to play it:

var mymusic:Sound = new mysound();
mymusic.play();

Next time, we will learn how to pause our sound, change the volume and more!

Related:

Sound class in Actionscript 3: Part 2
Sound class in Actionscript 3: Part 3
Sound class in Actionscript 3: Part 4
Sound class in Actionscript 3: Part 5
Sound class in Actionscript 3: Part 6

No comments:

Post a Comment