Sound, Part 2: Animation or Action 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, but not requiring a mouse event or other user interaction: for example, a sound that signals a collision between two objects in a game.

I. 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 produced in Lab 1, 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("http://iat.ubalt.edu/courses/
  idia619.185_Sp08/swf/soundDemos/animation/excuseMe.mp3");
  var snd:Sound;

The URLRequest object soundReq is connected to an external MP3 file named excuseMe.mp3. We're using a fully-qualified URL here, which we need in order to incorporate the SWF into this Web page, which uses Apache Server-Side Includes. Less exotic pages may allow a simpler, relative path:

  var soundReq:URLRequest = new URLRequest("excuseMe.mp3");

In either case, 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, is invoked whenever the ball touches any of the four 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 necessary.

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();
  }

II. Source files

The main movie file, animationSound.fla, and the class file, ballClass.as, can be found in the subdirectory animation, within soundDemos in the shared account on student-iat. Be sure to download the MP3 file excuseMe.mp3, if you want to test this code on your own system.

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.



University of Baltimore Logo

Last updated: 06/24/08 16:26:20
Copyright © 2008 School of Information Arts and Technologies