A few months ago I switch over to Flash CS4 using AS3 and it was completely different from what I had been using before (Flash MX using AS2). I've decide to write some mini tutorials just for my own reference and maybe it will help someone else out. First, here's a tutorial for how to use sound.
To play sound from an mp3 file:
// Import the necessary sound classes
import flash.media.Sound;
import flash.media.SoundChannel;
var snd:Sound = new Sound();
// create a URL request for your file
var req:URLRequest = new URLRequest("YOUR MP3 FILE");
// Load the file
snd.load(req);
// create a SoundChannel object.
// This will allow you to control your sound later so it's
// good to use instead of just playing the sound with
// the Sound object.
var channel:SoundChannel = new SoundChannel();
channel = snd.play();
To stop your sound:
channel.stop();
Optionally, you can create an event listener for when your sound is done playing.
function onPlaybackComplete(e:Event) {
// Do something
}
channel.addEventListener(Event.SOUND_COMPLETE,onPlaybackComplete);
To control the volume:
import flash.media.SoundMixer;
var vol = 0.5 // define the volume from 0 - 1
var stf:SoundTransform = new SoundTransform(vol);
channel.soundTransform = stf;
To play an embedded sound from your library:
- First, you need to go to the properties window for your sound.
- In the "Linkage" section, check off "Export for Actionscrpt" and "Export in Frame 1".
- Then, where it says, "Class", give it a name, for example, name it "mySoundClass"
- Where it says, "Base class", put in "flash.media.Sound".
Then, go to the first frame and instead of loading an mp3 file, put the following code:
var snd:mySoundClass = new mySoundClass(); // mySoundClass is the class name you gave your file above.
Everything else is pretty much the same as if using an mp3 file.