Part VI: Working with Audio

Overview

Up to this point, your exposure to audio in the Flash environment has consisted mainly of sounds that are attached to your movie's Timeline and cued when their host frames are played . This technique works well for cueing music, sound effects, and dialog in such a way that they line up in sync with an animation. The only disadvantage to this approach is that all sounds are bound to frames, within either a Movie Clip or your main Timeline. As a result, if a Timeline has sounds you need but is not currently loaded, you are forced to call it to the Stage, adding an extra and often unwanted step to the process. Flash changes all of this with ActionScript.

When Flash evolved to version 5, it introduced the Sound object. The Sound object is an element of ActionScript that allows you to have complete control over every sound in your movie, whether the sound is in a Timeline or not. Flash MX has continued the tradition with terms that allow you to load external sounds, manage sound playback, and track sound- related events. The Sound object opens the possibilities for interactive audio in Flash, and allows you to change every sound parameter dynamically through scripting rather than with keyframes and sync options.

 

Working with the Sound Object

The Sound object is one of ActionScript's predefined objects. You use it to control the playback parameters of sounds in your movie. The Sound object allows you to play and stop sounds, set their volume level, and change their position and volume in the left and right speakers . The Sound object also makes it possible for you to monitor the volume, panning, and effects applied to a particular sound. To use this object, it's important to understand what it is and how it works as part of the ActionScript language.

Understanding the Sound Object

As do all objects in ActionScript, the Sound object holds information about various components of your movie. Just as the MovieClip object holds information about the properties of a particular clip, and the Math object stores specifics of arithmetic, this Sound object stores information about a movie's sounds and their properties. More specifically , it stores information as to whether a sound is currently playing and, if so, how loud, in what speaker(s), and so on. To monitor or control a sound via ActionScript, you must create a new Sound object. Once a sound has an object associated with it, the object allows you to pass information to and from the sound.

Objects can encapsulate the specific attributes of an element in your movie and allow you to control them. They also serve as a medium of exchange. In the exchange, you must have currency ”something common that can be understood and used by both your movie and its objects. ActionScript refers to this kind of currency as methods . Methods are used to send and retrieve information between your movie and its objects. Every object has a particular set of methods that it implements. The Sound object has methods that check and set volume and panning, play (start), and stop active sounds in your movie. When you need to communicate with an object, you must use its methods.

Using the Sound Object

The first step toward working with the Sound object is knowing how to create a Sound object instance. Without it, you will have no means of communicating with a particular sound. When you create a new Sound object, it can be used to control:

§                       All sounds currently available in the Flash Player (all SWF files loaded_ in at various levels)

§                       All sounds currently available in the movie

§                       The sounds in a specified Movie Clip instance

§                       A sound you specifically attach to the object

Depending on how you create the object, you will be able to use it for any of these applications. The generic constructor for a Sound object is as follows :

  soundObjectName  =new Sound("targetInstance"); 

Here, soundObjectName is a placeholder for whatever you wish to call the object. targetInstance is an optional argument ( enclosed in quotes) for the function. If you plan to control the sounds in a particular Movie Clip, you must target the clip specifically.

To create an object for every movie currently available in the Flash Player, no target argument is necessary. Use this constructor:

  globalMovieSound  =new Sound(); 

Here, globalMovieSound is the name of a new object to control the sounds on all Timelines.

To create an object for all sounds in a Movie Clip or on a specific Timeline, you must create the object and specify a target argument as a string (in quotes):

 monkeyClipSound=new Sound("bananas"); 
 loadedSound=new Sound("_level1"); 

In the first example, an object named monkeyClipSound is created to control the attributes of sounds in the Movie Clip named bananas . The second statement creates an object named loadedSound for all sounds on the Timeline of the movie loaded at level1 .

When a Sound object targets a sound in another Timeline, the object can be used only to control the volume and panning of the sound. Play and stop don't work because the sound is bound to the frames of the Timeline where it resides. However, Sound objects can control individual sounds that reside in a movie's Library. To facilitate this, you must attach the sound directly to the object. To learn how to do this, see the section "Attaching Sounds with Linkage Identifiers" later in this chapter.

Controlling Sound Playback

Creating a Sound object is an essential step to controlling your sounds dynamically with ActionScript. Without the object, you have no means of issuing commands to the sound. After you construct an object for a specific sound, you are free to invoke the methods of the Sound object to control their playback.

Controlling a sound via ActionScript offers several advantages over the conventional frame-based sound cues. First of all, if you want to cue only a particular sound, you don't have to target a Movie Clip or Timeline to play a specific frame. In many cases, the Sound object allows you to refer to a sound specifically, and you can cue it without having to play the frame where it resides in your movie. Conventional ActionScript has provisions for you to stop all sounds in your movie. In addition to providing this same stop feature, the Sound object allows you to start all the sounds in your movie with a single set of script commands.

The other advantage of controlling a sound through ActionScript is greater flexibility. Any element of your movie that uses scripting represents an opportunity to control sound playback. As graphic elements of your movie are dynamically manipulated or moved, you can echo these changes in your sound scripting.

Here are some of the Sound object methods used to control sound playback:

start(secondsOffset, loops )      Used to cue sounds. start() can take two optional arguments. The secondsOffset argument can be used to start a sound from any point within the sound file. To start a 10-second sound at its halfway point, you would specify an offset of 5. The loops argument establishes the number of times a sound will play. If no loop is specified, the sound will play once (the default). To play it twice, enter a value of 2; enter 3 to play it three times, and so on.

 

Note  

To cue a sound using the start() method of the Sound object, the sound must first be exported from the Library using the Linkage option. To learn more about this, see the section "Attaching Sounds with Linkage Identifiers" later in this chapter.

stop("soundID")      Used to stop sounds. stop() will silence all sounds in the object that it is used to control. The optional argument soundID is used to stop sounds that were attached to the Sound object directly with symbol linkage.

To see specific examples using these methods, see the section "Playing and Stopping Sounds" later in this chapter.

Setting Volume and Pan Parameters Dynamically

Without the help of ActionScript and the Sound object, you are forced to cue sounds by placing them in frames of your main Timeline or a Movie Clip. The same is true for the parameters that affect a sound's volume and panning. To change this kind of information for a sound placed in a keyframe, you must use the Edit Envelope dialog box and drag the envelope handles into position (see Figure 25.1). Although this technique does give you a convenient graphical representation of the changes affecting a sound's envelope, the changes are permanent and cannot be altered after the movie is published. To make changes to an envelope effect, you have to go back to the keyframe where the sound is cued, open the Sound panel, and enter a new envelope shape.

click to expand
Figure 25.1: The Edit Envelope dialog box

ActionScript expands the possibilities tremendously by providing four methods for setting and monitoring the volume and pan parameters of a sound. And because this can all be accomplished via scripting, you have the potential to dynamically change volume and pan information at any time and from any location in your movie. Here are the methods:

setVolume(volume)      Controls the volume of a sound's playback. Specify the argument volume between 0 (muted) and 100 (full volume). The default volume setting is 100.

getVolume()       Monitors the volume of a Sound object. This method returns a value between 0 and 100, representing the current volume of the object.

setPan(pan)      Sets the pan position for a Sound object. The argument pan determines where the sound is positioned. A value of 100 indicates that the sound is panned hard right (panned completely to the right speaker); “100 indicates that the sound is panned hard left (panned completely to the left speaker); and 0 indicates that the sound is centered (the default pan position). Once an object's panning has been set, it will remain in that position until it is changed.

getPan()      Monitors the pan position of a Sound object. This method returns values ranging between “100 (hard left) and 100 (hard right), which represent the pan position of the object. The value 0 (the default) means that a sound is shared equally between the two speakers.

To see specific examples using these methods, see the section "Setting Volume and Pan Levels" later in this chapter.

Creating Special Stereo Effects

ActionScript provides a special Sound object method that allows you to create unique effects with stereo sounds in your movie; it is called setTransform() . While the effects it creates are similar to those accomplished with panning, there is a bit more to this method. You might remember from Chapter 22 that stereo sounds are sounds that have been mixed with different components in the left and right speaker channels. For instance, a barbershop quartet might have the bass and lead voices mixed more heavily in the left channel, while the baritone and tenor voices are mixed more to the right. If you were to listen to only one channel of a stereo mix, you would hear an incomplete rendition of the audio because it would be missing about half of its components.

The setTransform() method doesn't affect sounds directly. To use it, you must create a generic object that applies the transform information to the sound object you wish to alter. The generic object (call it a transformer ) allows you control each channel of a stereo mix and assign output values for each as percentages. For each channel of stereo sound, the transformer object has two properties, one that controls a channel's left output, and one for the right. This gives you a total of four properties that can be used to alter the stereo composition of a sound. See Table 25.1 for a rundown of the generic object ( transformer ) properties.

Confused? Take a look at two examples of property settings to see how they would work in context. The following properties play a stereo sound as true stereo; all of the left information is played in the left speaker, and all right information is played in the right speaker:

 ll = 100 
 lr = 0 
 rr = 100 
 rl = 0 

These next property settings swap the left and right channel information to create a reverse stereo effect; all left information is played right, and all right information is played left:

 ll = 0 
 lr = 100 
 rr = 0 
 rl = 100 

Of course, by changing the values assigned to each property, you can create many different kinds of interesting stereo effects.

Once the properties have been stored in the generic transformer object, it is passed to the sound object via the setTransform() method. Here is a breakdown of the method's syntax:

setTransform(transformer)      Applies the properties stored in the transformer object to a sound object.

getTransform()      Retrieves the properties applied to a sound object in the last setTransform command.

 On the CD      For an example of using the setTransform() method and creating a generic transformer object, see setTransformer.fla in the Chapter 25 folder of this book's companion CD.

Table 25.1: Properties for the transformer Used with setTransform()

Property

Value

Description

ll

0 “100

Percentage of left channel sound to play in the left speaker

lr

0 “100

Percentage of right channel sound to play in the left speaker

rr

0 “100

Percentage of right channel sound to play in the right speaker

rl

0 “100

Percentage of left channel sound to play in the right speaker

 

Cueing Sounds with the Sound Object

The Sound object provides you with a great deal of flexibility in controlling sound playback. You will find that it offers substantial advantages over conventional frame-based sound cues because you can cue sounds at any time and manipulate their attributes dynamically. Now that you know what the Sound object is and how it works, you're ready to put it to use in the context of your Flash projects. This section shows you how to use the Sound object to export and attach a sound from your movie's Library and then cue it in your movie.

Attaching Sounds with Linkage Identifiers

One of the most useful functions of the Sound object is that it allows you to play sounds that are not directly inserted in a Timeline keyframe. However, before you can do this, you must attach the sound to the object you are using to cue the sound and control it. By attaching a sound, you are adding it to your movie while it is running. In some ways, this is the ActionScript equivalent of cueing a sound from a frame. The main difference is that when a sound is attached, it is done with ActionScript. Consequently, it can be paired with button clicks, keystrokes, and other types of user interaction.

To attach a sound to a Sound object, you must first export the sound from your movie's Library. Here are the steps:

1.     In your movie's Library, highlight the name of the sound you wish to export.

2.     In the Options pop-up menu, select Linkage. You can also Ctrl+click (Mac) or right-click (Win) and select Linkage from the context menu. The Linkage Properties dialog box opens (see Figure 25.2).

click to expand
Figure 25.2:
The Linkage Properties dialog box is used to export a sound from the Library so that it can be attached to a Sound object.

3.     Check the button next to Export for ActionScript and give it a unique name in the Identifier box. The Identifier is the name you will use to attach the sound to a Sound object. In Figure 25.2, the exported sound will be attached to an object as libSound .

Notice that the option labeled Export in First Frame is checked by default. This means that the sound will be added to the first frame of your movie when it is loaded into the Flash Player. If you are using large audio files, this puts a heavy burden on the first frame, because the sounds and other elements in frame 1 must be loaded before any other content. Ultimately, this can result in a very long initial download that must take place before a preloader is encountered . To learn how this can be avoided, see "Adding the Audio Files" in Hands On 6.

4.     Click OK when you are finished. The sound is now ready to be attached to a Sound object.

 

Note  

The Linkage Properties dialog box is also used to include sounds as a Shared Library asset. Shared Libraries allow you to exchange common files between several different Flash movies. To learn more about creating and working with Shared Libraries, see Chapter 7.

After you export the sound from the Library, you are able to attach it to a Sound object. This step officially associates the sound with an object, which in turn can be used to control the various parameters of the sound's playback. An object can have only one sound attached at a time. Attaching a new sound to an object will replace any sounds the object previously contained. To attach a sound, you use the attachSound method, which has this syntax:

    sndObj  .attachSound("  idName  ") 

Here, sndObj is a placeholder for the name of the object to which you will attach the sound. The argument idName (a string, entered in quotes) is used to declare the name of the identifier associated with the exported sound you wish to attach.

The following example creates a new Sound object called movAudio and attaches the sound exported from the Library as libSound :

 movAudio=new Sound(); 
 movAudio.attachSound("libSound"); 

After completing these steps, any methods applied to the movAudio object will affect the playback of the sound file exported as libSound .

Playing and Stopping Sounds

Two of the most important methods of the Sound object are those used to play and silence sounds. After all, a sound has to be cued (or stopped and recued) before you can make any audible changes to its panning, volume, or stereo composition. To cue a sound from scratch:

1.     Go through the steps of exporting the sound from the Library and assigning it an identifier. To learn more about this, see the preceding section.

2.     Once you have exported the sound, you can add the following script statements to the script of a button, frame, or other movie element:

3. mySound=new Sound();

4. mySound.attachSound("bkgdLoop");

mySound.start(0,999);

This script example does three things:

§                       It creates a new Sound object named mySound .

§                       It attaches the sound exported as bkgdLoop to the object.

§                       It cues the sound from its beginning and loops it 999 times.

Assume for the moment that this object controls a sound that is 4 seconds long. To loop the sound 999 times from its halfway point, you would enter:

   mySound.start(2,999); 

This statement uses the secondsOffset argument to start the 4-second sound 2 seconds (or halfway) into the file. This becomes the new "beginning" of the audio file. Each new loop will start from this point.

Another variation on this would be to use a variable to set the number of loops for a particular sound. For example:

   loop=4 
 mySound.start(0,loop); 

In this example, the variable loop is initialized to 4 and will cause the mySound object to loop four times. However, because loop is a variable, you are able to manipulate its value with ActionScript in other portions of your movie. You can create some sort of interactive controller (slider, button, keystroke, and so on) that will increase or decrease the number of times a sound will loop when it is cued.

When playing sounds via the Sound object, you'll find that you can also exert a fair amount of control in stopping sounds. Consider the following statements:

   addASound=new Sound(); 
 addASound.attachSound("ambient"); 
 addASound.start(); 
 addASound.stop(); 

This script example does the following:

§                       It creates a new global Sound object named addASound .

§                       It attaches the linked sound ambient to the object.

§                       It cues the sound.

§                       It stops all sounds in the movie (because the object is global). If the addASound object were targeted to a specific level or Movie Clip, this final statement would stop only the sounds in that target clip.

The stop() method will also accept an argument in its parentheses; this argument is known as soundID . The argument is available so that you can silence a specific sound by referring to its symbol identifier. Consider the following examples:

These statements are on the main timeline:

   sound1=new Sound(); 
 sound1.attachSound("ambient"); 
 sound1.start(); 
 sound1.stop("ambient"); 

These statements are attached to a Movie Clip called effect_mc :

   onClipEvent (load){ 
   sound2 = new Sound(this); 
   sound2.attachSound("effect"); 
   sound2.start(); 
 } 

Here you see the same set of commands as before. The main difference is that the stop method uses an argument in its parentheses. In this case, even though sound1 is a global Sound object, the only sound that will be stopped is ambient . Because ambient is an attached sound, and because it is stopped explicitly, it will cease to play. Other sounds, such as effect , will continue playing. If the line read

   sound1.stop() 

then all sounds would cease playing. If the line read

effect_mc.sound2.stop()

then effect would cease, but others would continue. This is because sound2 was created on the effect_mc Movie Clip Timeline. Its sounds belong to (or are "scoped") to that Timeline because the Sound object was created using this .

 

Scripting to Control Volume and Panning

At this point, you have learned about the Sound object, how it is used, and how to cue sounds in your movie using ActionScript and the Sound object methods. The Sound object allows you to control all parameters of sound playback through scripting; this includes ActionScript techniques that can dynamically set the volume level and pan position of a sound in your movie. Using ActionScript to create different kinds of controllers or script calls, you are able to make changes to a movie's audio based on user interaction and various movie events. The best thing about this is that the changes can take place at runtime and be continually updated to match the interactive structure of your movie.

This section presents several key concepts that show you how to set volume and pan levels using ActionScript. Related to this, there are also techniques for creating audio fades and stereo effects. As are many of the examples presented in this book, these are germ ideas. The intention is that you grasp the basic concepts here and then take them to new heights in movies of your own. Dig in and, most of all, have fun! With the precise audio control that ActionScript adds to your movies, you will find an entirely new level of sound possibilities in Flash.

Setting Volume and Pan Levels

Volume and panning are two of the most important considerations when it comes to putting together an audio mix. By assigning each sound its proper level, you are able to create an ideal balance among all audio components of a movie: sound effects, music, dialog, and narration. Positioning a sound in the stereo field helps create an audio environment where each element has its own niche in the overall sound composition of your movie. With the help of ActionScript, this can all be done using a few simple lines of code that set the audio changes in motion.

When you manipulate volume and pan data in Flash, it is assumed that the sound you wish to affect is already playing. If a particular sound associated with the Sound object has not yet been cued, Flash will have nothing to control. However, once a sound is playing, you are free to use the methods of the Sound object to change its pan and volume attributes.

To set the volume level of a sound, you must use the setVolume() method. This method uses the dot operator to apply the volume information to the Sound object that you specify in your script. For example, to set the level of a sound to full volume, enter the following statement:

   myObject.setVolume(100); 

In this example, myObject is the name of the Sound object you will affect. This script example is often preceded by statements that create the Sound object myObject , attach a sound from the Library, and cue the sound using the start() method. Of course, these elements don't have to appear in the same script window as the setVolume() call, but they are usually executed in the movie before you can manipulate the sound's volume.

The setVolume() method can also be used to control a frame-based sound in your movie once it has started playing. Sounds attached to the frames of Movie Clips or to loaded SWF files can have their volume manipulated by the Sound object as well. Consider the following example:

 loaded=new Sound("_level1"); 
 loaded.setVolume(50); 

In this script, a new Sound object named loaded is created for the sound(s) of the SWF file playing on level 1. The setVolume() method lowers the level of these sounds to 50 percent of their total volume. Using this same syntax, the method can also target the volume of sounds in Movie Clip instances:

 sound3=new Sound("_root.intro.part2"); 
 sound3.setVolume(80); 

When you create a Sound object and enter the target path to a specific Movie Clip, the object can manipulate the volume (and pan) of any sounds that belong to its Timeline.

Controlling panning with ActionScript is very similar. The main difference is that the setPan() method takes both positive and negative numbers as arguments: “100 to pan hard left, and 100 to pan hard right. Consider the following script:

   bass=new Sound("bass_mc"); 
 bass.attachSound("fenderjazz"); 
 guitar = new Sound("guitar_mc"); 
 guitar.attachSound ("strat"); 
 bass.start(0,100); 
 bass.setPan(-75); 
 guitar.start(0,50); 
 guitar.setPan(75); 

This example cues two sounds after creating objects for each and attaching sound files from the Library. After each cue, the setPan() method is invoked to position each sound in an individual location: bass is panned mostly to the left, and guitar mostly to the right. I say mostly because each statement pans 75 percent of the sound to one speaker but leaves the remaining 25 percent in the opposite speaker. This pan configuration creates a fair amount of stereo separation for the sounds but still allows them to mingle and blend a bit.

 

Note  

You can also use setPan() to manipulate the panning of sounds in a Movie Clip or loaded SWF file. Simply enter a target argument in the parentheses when you create the Sound object. Any methods that manipulate that Sound object will apply to the targeted Timeline.

When setting the pan position of sounds, there is no "golden rule" to follow. Your best bet is to use your ears and develop a scheme that sounds good and fits your sound design goals. Remember, to correctly hear the panned sound, you must have a two-speaker stereo setup for your computer. If you don't have access to a set of speakers, headphones are always a good way to hear the subtle details of an audio mix.

Scripting Volume Controls

Once you have mastered the basics of manipulating volume settings, it's possible to combine that knowledge with what you already know about ActionScript, and create controls for changing the volume of various sounds in a movie. In previous chapters of this book, you used ActionScript to control many different parameters of graphic elements in your movie. The only difference here is that rather than use ActionScript to change the visual properties of Movie Clips, you will use it with the Sound object methods to change the properties of audio playback.

You already know that the setVolume() method is the part of ActionScript used to create changes in audio level. Here you will incorporate that technique with a few basic statements inside a Movie Clip to create a simple, yet flexible and powerful, volume controller.

 On the CD      To get an idea of what you will be creating, open the volumePanner.swf file found in the Chapter 25 folder of this book's companion CD. Although this example doesn't cover the specifics of creating this movie's graphic component, you can take a look at the finished Timeline in the volumePanner.fla file to get an idea of how it was constructed .

To create a set of volume control buttons , follow these steps:

1.     Prepare a couple of items before you begin working on this exercise:

§                               First, you need a sound to control. Import a sound to your movie's Library and export the sound symbol using the Linkage Properties dialog box. To learn more about linking sounds, see the section "Attaching Sounds and Symbol Linkage" earlier in this chapter.

§                               You also need at least one button to serve as part of your volume controller. One is sufficient because it can be used several times in the same Timeline. However, if you want to create two buttons, you can. To learn more about creating buttons, see Chapter 15.

2.     After you've set up your sound and button in step 1, begin by selecting Insert New Symbol. Name the symbol volume and select Movie Clip as its behavior. Click OK, and Flash jumps into Symbol Editing mode.

3.     Rename the first layer code and press F7 six times to create six empty keyframes in the layer.

4.     Click the first keyframe and press F9 to open the Actions panel. Enter the following statements:

5. cue=new Sound();

6. cue.attachSound("yourLinkedSound");

cue.start(0,100);

In this example, the reference yourLinkedSound is a placeholder based on whatever name you assigned to the sound you exported using Linkage Properties. Also, the name of the Sound object cue is arbitrary and can be changed if you want; just be sure to use the new name consistently throughout your scripts.

7.     Click the second keyframe and display the Actions panel once again. Enter these statements:

8. cue.setVolume(100);

stop();

These statements set the initial volume and stop the playback head at frame 2.

9.     In the remaining five keyframes, you will enter similar lines of ActionScript. See Table 25.2 for a listing of scripts and the keyframes they go in. When you've finished entering all the statements in their various frames, close the Actions panel and return to the volume Movie Clip Timeline. The role of these statements will be explained shortly.

10.     Insert a new Layer and name it buttons . The frames in this layer should span all seven frames of the code layer. Grab a button from your movie's Library and drag it to the Stage of the volume Movie Clip. Drag another button to the Stage and position it near the first button. If you use different buttons, you don't need to change them once they're on the Stage. The buttons used in volumePanner.fla are identical, but one has been rotated 180 to help show which one raises the volume and which one lowers it.

click to expand

11.     Click the button you wish to use as the "Lower Volume" button and open the Actions panel. Enter the following statements:

12.     on(release){

13.           if(_currentframe<7){

14.                   nextFrame();

15.           }

}

When this button is clicked, the script checks to see the position of the playback head in the Movie Clip. If it's at a frame number less than 7, the clip is told to advance a frame using the nextFrame() function. Your volume Movie Clip has seven frames. Once the clip is in frame 7, it doesn't advance if the button is clicked. Also, because the script uses nextFrame() , it advances the Timeline only one frame at a time. In the Timeline, each frame contains a statement that sets a new volume level. With each new frame, the clip stops and updates the volume level of the Sound object.

16.     Click the button you wish to use as the "Raise Volume" button and open the Actions panel. Enter the following statements:

17.     on(release){

18.           if(_currentframe>2){

19.                   prevFrame();

20.           }

21.     }

This button works similarly to the Lower Volume button. Each time the button is clicked, the script checks the current frame where the clip is stopped. If the frame is greater than 2, the playback head moves to the preceding frame number, or to the left across the Timeline. Because the setVolume statements increase in value from right to left, the Sound object volume gradually raises as the head moves closer to frame 2.

Table 25.2: Keyframe Statements for the Volume Movie Clip

Keyframe

ActionScript

3

cue.setVolume(80);

4

cue.setVolume(60);

5

cue.setVolume(40);

6

cue.setVolume(20);

7

cue.setVolume(0);

22.     Close the Actions panel and return to your movie's main Timeline. Grab an instance of the volume Movie Clip and drag it from the Library to the Stage. At this point, you don't need to assign an instance name to the clip. Select Control Test Movie to give this controller a spin. As you click the Lower Volume button, you should hear the sound level drop; conversely, the Raise Volume button should increase the volume of the sound.

Creating Audio Fade-Ins and Fade-Outs

What exactly is a fade-in or fade-out ? It's an audio effect that gradually raises or lowers the volume of a sound to either ease it up to full volume or taper it off to silence. As you've probably already guessed, fade-ins and -outs require you to manipulate the volume of a sound as you did to create a volume controller. This is true, but with one exception: Fades are gradual effects; once you set them in motion, they happen slowly over time. To create a fade, you must design a Movie Clip structure that can gradually take a sound from one volume extreme to another in a single step, rather than with the individual mouse clicks you used to create volume controls.

 On the CD      Open the file fadeInOut.swf or fadeInOut.fla from the Chapter 25 folder on this book's companion CD. Play around with the fade-in and fade-out buttons to see and hear exactly what happens with a fade controller. The process of creating a fade is simple, and based on what you already know about volume controls, you should easily grasp the concepts behind a fade controller.

To create controls that fade a sound in and out, follow these steps:

1.     Prepare a couple of items before you begin working on this exercise:

§                               Here again, you need a sound to control. Import a sound to your movie's Library and export the sound symbol using the Linkage Properties dialog box. To learn more about linking sounds, see the section "Attaching Sounds with Linkage Identifiers" earlier in this chapter.

§                               You need at least one button to serve as part of your fade controller. One is sufficient because it can be used several times in the same Timeline. However, if you want to create two buttons, you can. To learn more about creating buttons, see Chapter 15.

2.     Begin by selecting Insert New Symbol. Name the symbol fader and select Movie Clip as its behavior. Click OK, and Flash jumps into Symbol Editing mode.

3.     Rename the first layer code and enter 13 empty keyframes in the layer (you should have a total of 14 in the entire clip). Click the first keyframe and press F9 to display the Actions panel. Enter the following statements:

4. cue=new Sound();

5. cue.attachSound("yourLinkedSound");

6. cue.start(0,100);

cue.setVolume(100);

In this example, the reference yourLinkedSound is a placeholder based on whatever name you assigned to the sound you exported using Linkage Properties. Also, the name of the Sound object cue is arbitrary and can be changed if you want; just be sure to use the new name consistently throughout your scripts.

7.     Click the keyframe at frame 2 and enter a stop() function in the Actions panel. The remaining 12 keyframes will need fairly repetitive and similar statements. See Table 25.3 for a listing of each keyframe and its corresponding script.

This step completes your work for the fader Movie Clip. If you looked at the fadeInOut.fla file on the CD, you'll notice that there some graphic enhancements to the clip. These are optional and won't influence the functionality of the Movie Clip in your movie.

8.     Close the Actions panel and switch back to Movie Editing mode and your main Timeline.

9.     Drag the fader Movie Clip to your Stage and assign it the instance name fade in the Property Inspector.

click to expand

As it appears on the CD, fadeInOut.swf has a simple graphic element that represents an LED volume meter. Add this option if you want. If you followed the preceding step, the clip won't have any sort of significant graphical representation ”only a hollow circle to serve as a placeholder for the clip. The fade instance (as described in this lesson) is what you call a sound-only Movie Clip, meaning that the clip has sound(s), frame(s), and, in most cases, some ActionScript. Sound-only clips are ideal for holding and controlling audio. They can be targeted just as any other clip can; the only difference is that they don't have any kind of visual animated components.

10.     Create a new layer in the main Timeline and name it buttons . Drag two buttons to this layer of the Stage to serve as your fade-in and fade-out controls. If necessary, change one of the two buttons graphically so that it is distinguishable from the other. It should be clear which one will perform the fade-in and which one will perform the fade-out.

11.     Select the fade-out button and open the Actions panel. Enter the following statements:

12.       on(release){

13.           root.fade.gotoAndPlay(3);

}

This script targets the clip instance fade when the button is clicked and sends it to play at frame 3. The clip is sent to frame 3 because this is the button used to fade a sound out. Frame 3 is the frame where the volume begins to decrease (see Table 25.3). Notice, however, that there is no stop() function until the clip reaches frame 8. Between frames 3 and 8, the setVolume() method gradually decreases the volume of the sound. Then, once it has been set to a level of 0, the clip is stopped.

Table 25.3: Keyframe Statements for the Fader Movie Clip

Keyframe

ActionScript

3

cue.setVolume(80);

4

cue.setVolume(60);

5

cue.setVolume(40);

6

cue.setVolume(20);

7

cue.setVolume(0);

8

stop();

9

cue.setVolume(10);

10

cue.setVolume(20);

11

cue.setVolume(40);

12

cue.setVolume(60);

13

cue.setVolume(80);

14

cue.setVolume(100);_gotoAndStop(2);

14.     Select the fade-in button and open the Actions panel. Enter the following statements:

15.     on(release){

16.           root.fade.gotoAndPlay(9);

}

This script targets the clip instance fade when the button is clicked and sends it to play at frame 9. The reason should be clear. At frame 9, the volume is set to a level of 10; at frame 10, a level of 20; and so on. When the volume finally reaches a level of 100 at frame 14, the clip is sent to frame 2 and told to stop. It will sit there until another button click executes a script that runs it through the fade-in or fade-out animation once again.

17.     Select Control Test Movie and give your fade controller a try.

After testing this Movie Clip, you might find that the fade is either too short or too long for your purposes. You can fix this easily because there are a couple of strategies for tweaking the length of a fade.

If your fade is too short, do one of the following:

§                       Create a longer animation. If you put a greater distance between the keyframes that set volume levels, it will take Flash longer to execute the animation.

§                       Adjust your volume levels in smaller increments. In this exercise, you adjusted the sound in increments of 20 percent. Adjusting the volume in chunks of 5 percent or 2 percent will create a longer, more gradual fade effect.

§                       Lower the frame rate of your movie. The more slowly a movie's frames are played, the slower the individual setVolume() scripts are executed. Realize, however, that this will affect the speed of animated elements in your movie.

If you wish to shorten a fade (that is, decrease its length), simply reverse either of the techniques for lengthening the fade.

Scripting Pan Controls

Another important element of audio control is panning. By placing sounds in the stereo field, you can create a sense of space in the "world" of your movie. Panning assigns a source location to ambient sound effects and allows you to balance the positioning of multiple music tracks. And with the help of some additional ActionScript, the Sound object can be used to create controllers that dynamically adjust the pan position of a particular sound.

 On the CD      The finished file described in this exercise is the same that you used if you worked with the volume control buttons. If you haven't yet seen and heard this movie, open the volumePanner.swf or volumePanner.fla file found in the Chapter 25 folder of this book's companion CD. In addition to the volume button controls, there is a slider that, when moved left or right, adjusts the panning of the movie's sound accordingly . This exercise assumes that you are already familiar with the basics of creating a slider type of controller. If you would like to learn more about this topic, see Chapter 20.

To create a stereo pan controller:

1.     Prepare a couple of items before you begin working on this exercise:

§                               You need a sound to control; for this exercise, either a mono or stereo sound will do. However, because you will be manipulating the pan position, a mono sound really makes the most sense. Import a sound to your movie's Library and export the sound symbol using the Linkage Properties dialog box. To learn more about linking sounds, see the section "Attaching Sounds with Linkage Identifiers" earlier in this chapter.

§                               You will need one button to serve as the knob of your slider. To learn more about creating buttons, see Chapter 15.

2.     You can begin with the sound elements of this movie. You will create a new Movie Clip that is a sound-only clip. It will have one purpose: to cue a sound to play in this movie.

3.     Select Insert New Symbol. Give the symbol a name and set its behavior to Movie Clip.

4.     In this new Movie Clip, insert one empty keyframe in the first layer. In frame 1, enter the following statements:

5. cue=new Sound();

6. cue.attachSound("yourLinkedSound");

7. cue.start(0, 100);

 

Note  

If you are looking at the volumePanner.fla file found on this book's companion CD, the Sound object is created in the Movie Clip labeled volume , which has the instance name audio .

8.     Again, "yourLinkedSound" is a placeholder for the sound you exported from your movie's Library.

9.     In the second keyframe, attach a stop() function. This series of ActionScript commands creates a Sound object, attaches a sound from the Library, and plays the sound (all in frame 1). When the clip finishes executing these statements and moves to frame 2, the Movie Clip will stop, but the sound will continue to play.

10.     Return to Movie Editing mode and drag the clip onto the Stage of the main Timeline.

11.     Press Cmd/Crtl+F3 to open the Property Inspector and assign the instance name audio for the clip. This will allow you to target the clip so that you can control the panning of the Sound object you created in frame 1.

12.     With a Sound object in place, you can create the pan controller. Select Insert New Symbol. Name the symbol slider and select Movie Clip as its behavior. Click OK, and Flash jumps into Symbol Editing mode.

13.     Drag the button to the Stage of the slider Movie Clip and use the Align panel to position it in the exact middle of the Stage. Click the button to be sure it's selected. Use the Property Inspector to give it the instance name pan_button .

14.     Return to the Movie Clip's Timeline and rename the layer that contains the button controller . Then, add a new layer to the Timeline and name it code .

15.     Select the first empty keyframe of the code layer and press F9 to open the Actions panel. Enter the following statements:

16.     L=pan_button._x-50;

17.     T=pan_button._y;

18.     R=pan_button._x+50;

19.     B=pan_button._y;

mid=pan_button._x;

These statements help define the bounds of the slider. With these variables in place, you can complete the code for the pan controller:

pan_button.onPress=function(){

    startDrag(this,false,L,T,R,B);

    dragging=true;

}

pan_button.onRelease=function(){

    stopDrag();

    dragging=false;

}

pan_button.onReleaseOutside=function(){

    stopDrag();

    dragging=false;

}

this.onMouseMove=function(){

    if (dragging){

          root.audio.cue.setPan((pan_button._x-mid)*2);

          updateAfterEvent();

    }

}

These statements are nearly identical to those used in the slider example in Chapter 20. The main difference is the addition of the variable mid . If the clip is being dragged, it executes the following statement:

click to expand
Figure 25.3: The pan slider button (inside the slider Movie Clip) should have its guide line positioned behind it with the centers aligned.

_root.audio.cue.setPan((pan_button._x-mid)*2);

This pans the sound in your movie. This line targets the sound using an absolute path from the main Timeline and uses the setPan method to control the sound's left or right speaker position. The expression ((pan_button._x-mid)*2) returns a value between “100 and 100 based on pan_button 's current horizontal position. It subtracts the starting position ( mid ) from the current position ( _x ) and multiplies that by 2. Because the value for x lies between “50 and 50, the expression always returns “100 to 100.

20.     Now you are ready to assemble the final component of the slider controller. Create a new layer in the Timeline and name it track . Position this layer below the controller layer in the Movie clip Timeline.

21.     Draw a horizontal line 100 pixels long on the track layer. (You can use the Property Inspector to confirm the length.) This guideline is the other graphic component of the slider. Position it so that it is directly behind the button ( pan_button ), making sure that the two elements have their centers aligned (see Figure 25.3). Pan information in Flash can have a maximum value of 100 and a minimum of “100. By using a line graphic that is 100 pixels long, it will always appear that the slider button is "locked" to the line because pan_button starts in the middle of the line and can move 50 pixels left or right. When the values in this range are multiplied by 2, the pan values are updated accurately.

22.     Return to Movie Editing mode and drag the slider Movie Clip onto the Stage of the main Timeline. The pan slider is now complete! Select Control Test Movie to give it a try. As the sound plays, you should be able to drag the slider left and right, affecting the position of the sound in your stereo speakers or headphones.

 

Note  

If you like using sliders to control audio parameters, see Hands On 6 to learn how to create a mixing board application that uses slider controls for both volume and pan.

Loading External Sounds with ActionScript

One of the most compelling audio-related features of Flash is its ability to load external MP3 sound files. Rather than include a sound or group of sounds in your movie, you may now leave them outside your movie and call them in as needed.

This approach presents several advantages. First, sounds always add to the size of your final SWF file. So keeping sounds outside the final movie allows it to be smaller and might help it load more quickly. Additionally, because using external files cuts down significantly on movie file size, you'll be able to use a Library of sounds from which your audience can pick and choose. If they want to browse your movie while listening to classical music, reggae, western swing, or whatever, you can give them a host of files to choose from and then load the appropriate soundtrack for each visitor. External sounds can be loaded into a Flash movie from any location on the Internet. This means it's also possible to use Flash to create a forum for MP3 playback. Your audience can share the URLs of sounds that they want you and others to hear, making your movie a sort of MP3 jukebox.

The list of other possibilities goes on and on. As always, Flash is limited only by your time, budget, and creativity. The capability to load external MP3 files was originally introduced with Flash MX, so your movie must be published for Flash Player 6 or higher to take advantage of it. The required ActionScript terms are as follows:

Sound.loadSound ("url",stream)       Used to load external MP3s into the specified Sound object. loadSound() takes two arguments. Enter the externalMP3's URL as a string, and enter a Boolean value for stream . A setting of false means that the sound must load entirely before it can begin playback; true makes the sound a streaming sound, and it will begin to play once a sufficient amount has been downloaded.

Sound.getBytesLoaded()      Used to monitor the number of bytes in an external sound that have been loaded into the specified Sound object.

Sound.getBytesTotal()      Returns the total number of bytes for the specified Sound object. You can use the methods getBytesLoaded() and getBytesTotal() to create preloaders for external sound files.

 On the CD      Now that you are familiar with some of the new Sound object terms, you can get down to business. To make the following introductory procedure as simple as possible, we have prepared a starter file for you on this book's companion CD. Go to the Chapter 25 folder and open the file loadMP3.fla; copy it to your computer's desktop. Several additional steps have already been completed so that you can focus on the most important aspects of this technique.

To load an external sound, follow these steps:

1.     First, you must have a remote MP3 file that you can load. We recommend that you start with a small file so that while you're testing this procedure, you don't waste time waiting for a large file to load. Upload an MP3 file to your web server and write down the file's URL.

 

Note  

If you don't have a web server or an MP3 file to use, we've provided one for you. Use the_ following URL to link to the file savvySound.mp3 : http://www.vonflashenstein.com/_resources/savvySound.mp3 .

2.     In the loadMP3.fla file, select the first (and only) keyframe of Layer 1. Press F9 to open the Actions panel. You'll see something that resembles Figure 25.4.

click to expand
Figure 25.4: The ActionScript for the first keyframe of the loadMP3.fla file. You'll enter the URL for your external sound within the quotes of the loadSound statement.

3.     In line 2, notice the phrase "enterYourURLHere." Replace that phrase with the absolute URL of the MP3 file that you want to load into your movie. An absolute URL is written as http://www. myDomain.com / file.mp3 , where myDomain.com is the name of your domain and file.mp3 is the name of your MP3 file.

Line 1 creates the Sound object loaded . Line 2 uses the loadSound() method to load the external file that you just specified. false , an argument to loadSound() , determines that the loaded sound will behave like an event sound and must be completely loaded into memory before it can begin its playback.

4.     You'll notice that lines 3 “6 are blank. This is where you write a function that cues the sound once it has loaded. Enter the following statements starting at line 3:

5. loaded.onLoad=function(){

6.     loaded.start(0, 100);

7.     status.gotoAndStop(7);

}

When the Sound object loaded has completely loaded into the Flash player, its onLoad event occurs. This event executes the statements within the function: The sound is cued using start() , and a Movie Clip named status is skipped to frame 7 of its timeline. If you look at the Timeline of the status clip (see Figure 25.5), you can see that in frames 1 “6, it plays through an animation loop. This animation loops while the external MP3 is loading. Once the sound has loaded, it's sent to frame 7, where the animation stops.

click to expand
Figure 25.5: The Timeline of the status Movie Clip instance has an animation loop that plays while the MP3 is loading.

8.     There is a good deal of ActionScript in frame 1 that you don't have to write. Let's examine this script line by line:

Line 7       This creates a custom function named checkLoad() .

Line 8       This conditional statement checks the status of the sound while it's loading. It tests two things: whether the total byte count of the sound is greater than 0 and whether the bytes that have been loaded are equal to the total number of bytes. Only when both these statements are True (when the file has completely loaded) will the script execute line 9. Otherwise, when False, it skips ahead to lines 11 “14.

 

Note  

It's good to check whether Sound.getBytesTotal() is greater than 0. This helps prevent a sound that's slow to load from jumping the gun. If the sound hasn't loaded at all, it contains 0 bytes. Because it has loaded 0 bytes and contains 0 bytes, the statement 0==0 will obviously return True , and Flash will think that the sound has loaded completely.

Lines 11 “14       If the sound hasn't loaded completely into loader , a series of alternative statements will execute to show the load progress:

loadBytes is a variable storing the number of loaded bytes.

loadTotal is a variable storing the number of total bytes.

percent stores the percentage of the sound that has loaded.

bytes_txt is a text field in the status clip instance. Its contents are set to an expression that shows the number of loaded bytes over the number of total bytes and what percentage of the total sound this represents. This information is concatenated as a string and plugged into the text field.

Lines 11 and 12 use the Math.round() method to round the byte count to the nearest integer. Values are divided by 1,024 to give the kilobyte count.

Line 17       This line is probably the most important in the entire script sequence because it is responsible for calling the checkLoad() function. It creates the interval checker using the setInterval() function. This interval calls the checkLoad() function every 100 milliseconds . This means that, every one-tenth of a second, checkLoad() monitors the download progress of the MP3 and updates the movie accordingly.

Line 9       This statement falls within the block of code that executes when the MP3 has loaded completely. It uses the clearInterval() function to cancel the checker interval and stop monitoring the download progress of the MP3.

9.     Select Control Test Movie to give the loaded sound a try. As the sound is loading, the gold crescent spins , and the text field prints a numeric display of the loading sound's progress. Once the sound has finished loading, the spinning graphic stops, and the text in the Movie Clip changes to read "Welcome to the site."

If your movie doesn't work properly right away, here are a few things to check:

§                       Be sure you are connected to the Internet.

§                       Check the speed of your connection. A busy network will slow the loading process.

§                       Be certain that your URL to the external sound is correct.

This section has given you just a glimpse of the possibilities offered by external sounds. To learn about additional ActionScript terms that can enhance your movies and their ability to work with external sounds, see the "Sound Object" section of the ActionScript Reference on this book's companion CD.

 

Inspirational Design Model

Creating a truly interactive audio experience is a very difficult thing to do, not so much from a technical angle but from a point of communication. The designer's greatest task is deciding how to make the sound interactive while ensuring that it still works synergistically with the movie's graphic components.

Illustrator Molly Z's website ( www.mollyz.biz ) is an example of a site where imagery and sound come together to make a complete statement (see Figure 25.6). Each section has a unique color and design scheme. As visitors move from one content area to the next, the visual changes are complemented by variations in the audio: A triangle is added to the mix, a talking drum is removed, descending chords play on piano, and so on. Every musical transition and phrase is locked to an interactive event. When the audience clicks and moves to a new section, they hear as well as see the effects of their choice.

click to expand
Figure 25.6:
www.mollyz.biz is a Flash-based website that makes extensive use of interactive audio.

 



Flash MX 2004 Savvy. Also Covers Flash Professional.
Flash Mx2004; Also Covers Flash Professional; Savvy
ISBN: 0471789151
EAN: 2147483647
Year: 2003
Pages: 54

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net