Sound, Part 2: Event Sound
Click the on/off indcator to mute or unmute the sound.
This demonstration project shows a slightly more sophisticated use of the Sound object, playing a sound during a particular occurrence within a programmed animation. You may apply the technique explained here to any event controlled by code (so long as it does not require a mouse event or other user interaction). So, this technique could be used for sound that signals a collision between two objects in a game. Hint.
1. Code
As you can see, we've dusted off our old bouncing-ball project for this demo. The class file in play is none other than ballClass, as we wrote it long ago, with only a few additions.
For starters, we've added two importations required by the Sound object:
import flash.net.URLRequest; import flash.media.Sound;
We've also added some necessary variables:
var soundReq:URLRequest = new URLRequest("excuseMe.mp3");
var snd:Sound;
The URLRequest object soundReq is connected to an external MP3 file named excuseMe.mp3. We assume the MP3 file is stored in the same directory as the SWF.
A few other changes occur in the reSlope() custom method, which you may recall, comes into play whenever the ball touches any of the screen boundaries. Here's what's added:
snd = new Sound(); snd.load(soundReq); snd.addEventListener(Event.COMPLETE, soundGood);
Note that we create a new instance of the Sound object, called snd, each time the ball hits a boundary. We have to do this, and repeat the load() method, for each occurrence. This is cumbersome, but absolutely necessary.
If you try to replay a sound without reloading, you will generate an error.
Finally, we add an event listener for the COMPLETE event, just as we did in the background sound project. Its code is just the same as before:
function soundGood(event:Event):void
{
snd.play();
}
2. Source files
Source files for all the Sound demos presented this week are contained in a Zipped archive called soundDemos.zip, available from the code resources page.
For this demo, the main movie file, animationSound.fla, the class file, ballClass.as, and the sound source, excuseMe.mp3, can be found in the subdirectory animation, which unpacks with the Zip archive.
You'll also find a second class file, btnClass.as. This controls the on/off switch we've added to the project in the interest of sanity. (That talkatative ball gets old very quickly.) As you look through the code for ballClass, you'll see some slight variations from the way the code is described above. These allow the button to do its thing.
|
|