Hack 56 Real-Time Sound Effects

figs/moderate.gif figs/hack56.gif

Save bandwidth by creating sound effects in real time on the client side. Add reverb and other effects to increase the variety of sounds available.

The Sound class allows you to play a sound with an offset via Sound.start( ):

Sound.start(offset, loops);

Although that causes the sound to start playing offset seconds into the sound and repeat loops times, there is no direct way of playing a sample with a start and stop offset. The following code creates such a method, Sound.startEnd(startTime, endTime):

Sound.prototype.startEnd = function(startTime, endTime) {

  var duration = (endTime-startTime)*1000;

  this.start(startTime, 1);

  this.endSound = setInterval(endTimer, duration, this);

};

endTimer = function (arg) {

  arg.stop( );

  clearInterval(arg.endSound);

};

mySound = new Sound(this);

mySound.attachSound("UISound");

mySound.startEnd(0.5, 0.7);

The Sound.startEnd( ) method allows you to use small sections of any existing sound you already have in the Library as UI click sounds, saving you the need to create them separately.

Being able to cut sounds in this way is also useful when you want to create interactive soundboard mixing decks. It is also a good way to emulate the fast forward/rewind function seen on some CD players, whereby the CD player will play a 1-second sample for every 10 seconds of recorded sound, thus allowing you to search quickly through the CD material.

Another trick used to hide the fact that you are using the same basic sounds is to add real-time effects to them. The following code adds a reverb effect by playing two slightly time-displaced versions of the same sound:

mySound = new Sound(this);

mySoundEcho = new Sound(this);

mySound.attachSound("UISound");

mySoundEcho.attachSound("UISound");

mySound.start(0, 1);

mySound.start(0.1, 1);

Changing the last line to:

mySound.start(0.001, 1);

creates a phase-shift effect.

You can also overdrive the sound volume to more than 100% to create distortion effects:

mySound = new Sound(this);

mySoundEcho.attachSound("UISound");

mySound.start(0, 1);

mySound.setVolume(200);

Flash allows you to define negative volume levels. This produces a 180-degree-phase-shifted version of the original signal, which can be used to create phased effects (especially if you combine them with the reverb effect). This does, however, depend on the user having good audio equipment and well-set-up speakers (not as likely as you may think!).

As you can see, a number of avenues allow you to make the most of only one or two sounds in your SWF via real-time sound processing. This can be particularly important if you are asked to write Flash content (with sound) for extremely bandwidth-limited applications, especially banner ads, which are often limited to less than 12 KB.