13.10. Adding Sounds to Buttons and UI Components

Problem

You want to add sounds that play when the user clicks a button or when a UI component selection is made.

Solution

Add the sound to the movie by attaching it from the Library or by loading an external MP3. Create a Sound object to target the sound. Then add a call to start( ) within the button’s or component’s handler function.

Discussion

You can use sounds in conjunction with buttons and UI components to alert the user that something has happened (i.e., a selection has been made, a button has been pressed, etc.). To accomplish this, you need to complete the following three steps:

  1. Add the sound to the movie, either programmatically by attaching the sound from the Library or by loading the sound from an external MP3. If you are loading the sound, be sure to do so on a keyframe of a timeline prior to when you want to use the sound. You should make sure you give Flash enough time to download the sound.

    // Create a sound holder movie clip.
    this.createEmptyMovieClip("soundHolder_mc", 1);
    
    // Create the Sound object.
    click_sound = new Sound(soundHolder_mc);
    
    // Attach a sound from the library.
    click_sound.attachSound("MySoundSymbol");
  2. Call the Sound.start( ) method from within the handler function or method for the button or UI component. For example, if you want the sound to play when a push button is clicked, place the call to start( ) inside the click handler function:

    function onClick ( ) { click_sound.start( ); } myPushButton.setClickHandler("onClick"); ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.