Attaching Sounds and Controlling Sound Playback

In non-dynamic 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 objects, you'll learn how to add sounds and control their playback on the fly.

When you create a Sound object 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 anytime 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 objects 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 object named music. The next line attaches the rockMusic sound (in the library) to this Sound object. The third line starts the playback of this Sound object, which in effect starts the playback of the rockMusic soundtrack because it's attached to this Sound object. 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.

TIP

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 object, 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 has been made. A script we'll be adding shortly will play this animation in various circumstances.

    The Score Fields layer contains two text fields named 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 where 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.

    graphics/17inf19.gif

  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.

    graphics/17inf20.gif

    The reason we've 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've assigned 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 object, insert the following line of script:

    
    var dynaSounds:Sound = new Sound();
    
    

    This step creates a new Sound object called dynaSounds. This Sound object will eventually be used to randomly play one of the sounds in the library (Sound0, Sound1, or Sound2).

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

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

    
    var netSound:Sound = new Sound ();
    
    

    graphics/17inf21.gif

    This line creates another Sound object 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 object, 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 object can change. The last line of the script plays the current sound attached to this Sound object. 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");
    
    }
    
    

    graphics/17inf22.gif

    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 object, 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 object, 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 object 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'll describe in Lesson 18, "Loading External Assets."