Attaching Sounds and Controlling Sound Playback


In nondynamic projects, sounds are placed directly on and controlled from the Timeline. If you want a sound to play in your movie, you must drag it from the library onto the Timeline and then indicate when and how long it should play, as well as how many times it should loop on playback. Although this may be a fine way of developing projects for some, we're ActionScripterswe want control! That's why in this exercise we show you how to leave those sounds in the library and call on them only when you need them. Using other methods available to Sound instances, you'll learn how to add sounds and control their playback on the fly.

When you create a Sound instance in Flash, one of the most powerful things you can do with it is attach a soundin essence, pulling a sound from the library that can be played or halted any time you want. To do this, you must assign identifier names to all the sounds in the library. After these sounds have identifier names, you can attach them to Sound instances and control their playback and even their volume and panning, as we discussed earlier in this lesson.

For example, let's assume that there's a music soundtrack in the project library with an identifier name of rockMusic. Using the following code, you could dynamically employ this sound in your project and control its playback:

   var music:Sound = new Sound();    music.attachSound("rockMusic");    music.start(0, 5);


When executed, the first line of this script creates a new Sound instance named music. The next line attaches the rockMusic sound (in the library) to this Sound instance. The third line starts the playback of this Sound instance, which in effect starts the playback of the rockMusic soundtrack because it's attached to this Sound instance. The 0 in this action denotes how many seconds into the sound to start playback. For example, if the rockMusic soundtrack includes a guitar solo that begins playing 20 seconds into the soundtrack, setting this value to 20 would cause the sound to begin playback at the guitar solo rather than at the sound's beginning. The second value in this action, which we've set to 5, denotes how many times to loop the sound's playback. In this case, our soundtrack will play five times before stopping.

Note

You can set all of these values using variables or expressionsopening a world of possibilities.


In the following exercise, we show you how to attach a random sound from the library to a Sound instance and trigger its playback whenever the mouse button is pressed. We'll also set up our script so that pressing any key halts the sound's playback.

1.

Open basketball5.fla.

Continue using the file you were working with at the end of the preceding exercise.

The Ball Score and Score Fields layers of our project contain assets we'll use in this exercise. The Ball Score layer contains a movie clip instance named score_mc above the basketball goal. This instance contains two frames labeled Empty and Score. At the Empty frame label, the instance is, well, empty. This is its state when it first appears in the project. At the Score label is a short animation used to simulate the basketball going through the net as if a score were made. A script we'll be adding shortly will play this animation in various circumstances.

The Score Fields layer contains two text fields: indiana_txt and northCarolina_txt. These fields will be used to display updated scores under various circumstances. (This will become clear shortly.)

Before we begin scripting, we need to look at some of the assets in the library.

2.

Choose Window > Library to open the Library panel.

The library contains a folder called Dynamic Sounds, in which you'll find four sounds that have been imported into this project. These sounds exist only within the library; they have not been placed on our project's Timeline yet.

3.

Click on Sound 0 to select it. From the Option menu in the library, choose Linkage.

The Linkage Properties dialog box appears. This is where you assign an identifier name to the sound.

4.

Choose Export for ActionScript from the Linkage options, and give this Sound an identifier name of Sound0.

The reason we used an identifier name ending in a number is that our script generates a random number between 0 and 2: when 0 is generated, Sound0 plays; when 1 is generated, Sound1 plays; when 2 is generated, Sound2 plays. The number at the end of the identifier name is therefore crucial.

After you assign an identifier name to the sound, click OK.

5.

Repeat Steps 3 and 4 for Sound 1 and Sound 2 in the library. Give Sound 1 an identifier name of Sound1 and Sound 2 an identifier name of Sound2.

Note

Library item names can contain space; identifier names cannot. When assigning identifier names, follow the naming rules that apply to variables.

At this point, you have given three of the sounds in the Dynamic Sounds folder identifier names of Sound0, Sound1, and Sound2. The other sound, named Nothing but Net, has already been given an identifier of Net. This sound will be used in a moment to simulate the sound that a basketball net makes when a ball swishes through it.

6.

With the Actions panel open, select Frame 1 of the Actions layer. After the line of script that creates the bounce Sound instance, insert the following line of script:

  var dynaSounds:Sound = new Sound();


This step creates a new Sound instance called dynaSounds. This Sound instance will eventually be used to randomly play one of the sounds in the library (Sound 0, Sound 1, or Sound 2).

Notice that when we created this Sound instance, we didn't associate it with a Timeline. This means that our new Sound instance will be associated with the entire projecta "universal" Sound instance, so to speak.

7.

Add the following line after the script added in Step 6:

  var netSound:Sound = new Sound ();


This line creates another Sound instance named netSound that will be used to play the sound in the library with an identifier of Net.

8.

Add the following lines at the end of the current script:

  this.onMouseDown = function() {     var randomSound = random(3);     dynaSounds.attachSound("Sound" + randomSound);     dynaSounds.start(0, 1);   }


This onMouseDown event handler causes these lines of script to be triggered whenever the mouse is clicked anywhere on the stage. The expression random(3); generates one of three values between 0 and 2 and assigns this value to the randomSound variable. The next line attaches a sound from the library to the dynaSounds Sound instance, based on the current value of randomSound. If the current value of randomSound is 2, this would be the same as writing the following line of script:

   dynaSounds.attachSound("Sound2");


With each click of the mouse, a new number is generated, and the sound attached to this Sound instance can change. The last line of the script plays the current sound attached to this Sound instance. For the two parameters of this action, 0 causes the sound to play back from the beginning; the second parameter value of 1 causes the sound to play back once.

9.

Insert the following conditional statement within the onMouseDown event handler, just after dynaSounds.start(0, 1);:

   if(randomSound == 0){      northCarolina_txt.text = Number(northCarolina_txt.text) + 2;      netSound.attachSound("Net");      netSound.start(0, 1);      score_mc.gotoAndPlay("Score");    }else if(randomSound == 1){      indiana_txt.text = Number(indiana_txt.text) + 2;      netSound.attachSound("Net");      netSound.start(0, 1);      score_mc.gotoAndPlay("Score");    }


Because this conditional statement was placed within the onMouseDown event handler, it's evaluated every time the mouse button is pressed, and one of the sounds in the library is randomly played (as discussed in Step 8).

Before we explain what this conditional statement does, it's important that you realize how the three sounds in the library sound. The sound with an identifier of Sound0 is a clip of a booing crowd. Sound1 is a crowd cheering! Sound2 is a referee's whistle. Because this project was built with the Indiana basketball fan in mind, whenever Sound0 (booing) is attached to the dynaSounds Sound instance, we want team North Carolina to score two points, the cumulative total of which will be displayed in the northCarolina_txt text field instance in the upper-left corner of the stage. Whenever Sound1 is attached (cheering), team Indiana is given two points, displayed in the indiana_txt text field. When Sound2 is attached, neither team gets a point.

So how do we know which sound is being attached with each mouse click? Simpleby evaluating the value of randomSound, which is what the conditional statement does. If it has a value of 0, Sound0 has been attached, and team North Carolina has scored. If it has a value of 1, Sound1 has been attached and team Indiana has scored.

With that in mind, the conditional statement says that if randomSound has a value of 0, update the value shown in the northCarolina_txt text field to its current value plus 2, attach the sound in the library with the identifier of Net to the netSound Sound instance, play that sound, and send the score_mc instance to the frame labeled Score. All this transpires to give the realistic feel of team North Carolina scoring a point (which will happen very rarely!).

If randomSound has a value of 1, the second part of the conditional statement is executed, which essentially performs the same actions as the first part, except that team Indiana's score is updated.

10.

Add the following lines at the end of the current script (below the onMouseDown event handler):

  this.onKeyDown = function() {     dynaSounds.stop();   }   Key.addListener(this);


The onKeyDown event handler causes this line of script to be triggered whenever a key is pressed. When this action is executed, playback of the dynaSounds Sound instance is stopped, regardless of where it is in its playback. The last line causes the Key object to listen for this event.

11.

Choose Control > Test Movie to see how the movie operates.

In the testing environment, clicking the mouse causes a random sound from the library to play. The sound stops if you press a key while the sound is playing.

12.

Close the testing environment to return to the authoring environment. Save the current file as basketball6.fla.

This step completes the project! You should now be able to see how dynamic sound control enables you to add realism to your projectsand in the process makes them more memorable and enjoyable. You can do all kinds of things with sounds, including loading them from an external source, which we described in Lesson 13, "External Data Connections."




Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

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