devxlogo

FlashSound API: The Sound of Invisible Flash

FlashSound API: The Sound of Invisible Flash

ave you ever wanted to add interactive sound and backing music to a Web site but were unable to use Flash because you didn’t require any visual presentation? Now there’s a new way to “sonify” Web sites?the FlashSound Javascript API. The FlashSound API allows you to add interactive sound to a Web site by using the nearly ubiquitous Flash player to play sound-only invisible movies. The benefit is that you can create a Web site using easy-to-maintain HTML/JavaScript and conventional Web graphic formats while simultaneously playing interactive sound via Macromedia’s Flash Player. Because sound-only movies have no user interface, they don’t change your layout and they don’t rely upon Flash graphics to work.

Using the FlashSound API you add interactive sound to links, graphics, and buttons on your site and any user with the Flash 4 Player or better installed can hear them. Best of all, users who don’t have the Flash Player installed can see and use the same pages, silently, without any problems. This means there’s no need to create a separate non-Flash version of your Flash-enabled Web site; you merely have the option now to add interactive, invisible sound to an existing site.

What Is the FlashSound API?
The FlashSound API is a small JavaScript library developed by Sonify.org that enables you to trigger interactive audio from ordinary HTML pages, using the Flash Player. The FlashSound API handles browser detection, player detection, and SWF embedding for you. With some simple JavaScript code you can enable backing music or interactive sound in any Web site.

What do you need for this tutorial?
This tutorial is intended for developers who are familiar with HTML and JavaScript but are new to Flash. You should be up and running in a matter of minutes.

Download and install the free 30-day trial Flash Authoring Application from Macromedia.

Acquire audio samples (wav for Windows/aiff for MacOS) either from the Web, a CD, or from the Flash 5 Sound Common library.

Try these examples.

Warnings:
Do not play stream sounds with the window.onload event. If you specify a stream sound in the onLoad event, the browser will download the entire file (treat it as a download) rather than play the file as a stream.
Do not loop stream sounds with the sound panel. This replicates the sound within your movie, drastically increasing file size. Generally, you should loop only download sounds.
To control sound playback within the browser, create a sound-only movie to contain your sounds. Each sound has a corresponding sound-only movie clip and each movie clip must have an instance name. Use the FlashSound API code template to easily add sound to your site. Remember that each embedded SWF must have its own FlashSound instance name and embedSWF( ) statement. Use the TGotoAndPlay( ) method to control download sounds and the TPlay( ) and TStopPlay( ) methods to control stream sounds.

Create a Sound-Only Movie: Prepare the Library
Before you “sonify” a site with the FlashSound API, you need to create the sound-only movie that contains your sounds. The movie contains a movie clip for each sound. The first step in creating these clips is to prepare your movie’s library. The library contains your sounds and copies of a special movie clip symbol that supports interacting with sound. Each sound in the library must have an associated copy of this special movie clip. You can interactively start and stop sound-only movie clips using the FlashSound API. To create your library:

Download the Sound_Only_Movie_Clip_v2.zip. Unzip the file and place the Sound_Only_Movie_Clip_v2.fla in the Libraries folder of the Flash application folder. (You can replace the “_” character with regular spaces after you download the file).

Launch Flash and create a new movie. Open the Windows menu and select Common Libraries, choose Sound Only Movie (see Figure 1).

Open your movie’s library window. Drag the sound-only mc v2 icon on to your movie’s library window (see Figure 2).

Import one or more sounds into Flash. Under the file menu, choose Import and then Browse to find your sound (.wav for windows/.aiff for MacOS). Open your movie’s library window. Your library window should contain a movie clip symbol named “sound only mc v2” and a sound symbol for each sound you import (see Figure 3).

Rename the sound-only mc v2 symbol by single-clicking the text name and typing a new name in the highlighted area. The new movie clip symbol name should be descriptive of its corresponding sound. This will make it easier to manage your sounds as your library grows (see Figure 4).

Create a Sound-Only Movie: Set the Stage
After you prepare your library, the next step to create a sound-only movie is to add your movie clips to the stage. To interactively control a movie clip, it must be on the stage and have a unique “instance name.” Each movie clip on the stage is a container for sound.

To add a movie clip symbol to the stage, drag it from the library window to the stage. Your stage should show a small circle, which is how Flash represents movie clips without graphics (see Figure 5).

Figure 6.
Select the circle and then type an instance name in the Instance Panel. A valid instance name must not have spaces, must not start with a number, and should be unique. Choose an instance name that is similar to the sound it will contain. You will use this instance name, later on, to control sound playback with the FlashSound API (see Figure 6)

Create a Sound-Only Movie: Add Sound
After you add a movie clip to the stage and give it a unique instance name, you can begin to add sound. Each movie clip on the stage is a container for sound. You add sound to a movie clip by viewing the movie clip’s timeline and attaching sound to certain frames within the timeline. Timelines are created automatically by the API and you need not alter the structure of these timelines except to attach sound to specific frames..

Double click a circle on the stage. You should now see the pre-built timeline for this movie clip. The only change you make is to add the same sound to (for example) frames 5, 10 and 11 (see Figure 7).

Figure 9.
Click in frame 5 of the Sound Layer and choose a sound from the Sound Panel. Set this sound to “stop” under the sync options. Flash displays a black square for sounds set to “stop” sync (see Figures 8 and 9).

Click in frame 10 of the Sound Layer and choose the same sound as frame 6. Set this sound to “stop” sync also.

Add the same sound to frame 11 of the Sound Layer and set the sound to event or start sync in the Sound Panel. You should now see the wave form of the sound starting in frame 11 (see Figures 10 and 11).

Tip: To see the entire wave form of your sound, click the last white frame in the Sound Layer and drag it to the right.


Congratulations! You just created a sound-only movie clip. For technical information on how this sound-only movie clip works, read Flash Interactive Sound Design.

Create a Sound-Only Movie: Add More Sounds
A movie typically contains several sound-only movie clips; each represents a sound that you can control using the FlashSound API. To add more sounds to your movie:

  • Import more sounds as needed.
  • Drag a copy of the sound-only mc v2 to your library window.
  • Rename the sound-only mc v2 with a name that corresponds to the new sound you are adding.
  • Return to the main timeline by clicking the Scene 1 button in the upper left corner of the main window. This ensures that all of your sound-only movie clips are in the same place.
  • Drag the newly-named movie clip from the library window to the stage, give it a unique instance name, and add a sound to its timeline (see Add Sound).
Repeat these steps for each sound you want to control with the FlashSound API.

After creating your sound-only movies, your stage should have one circle representing each sound that you want to control, and each movie clip should have a valid unique instance name in the Instance Panel. All of your sound-only movie clips should be visible in Scene 1 of the main window and in frame one (see Figures 12 and 13).

Create a Sound-Only Movie: Compress Sound
After you are finished importing sounds and creating sound-only movie clips, you should apply compression to each sound in the Library window. Just like graphic compression, audio compression makes Web sites load faster.

Double-click the speaker icon of a sound in the Library window.

In the Sound Properties dialog box choose set compression to MP3, select a bit rate, and set the quality to Best. The lower the bit rate, the smaller the audio file size; however, lowering the bit rate also diminishes sound fidelity. Some sounds compress with less apparent fidelity loss than others. You should experiment with the compression settings for your sounds to see which settings work best for you (see Figure 14).

Here’s the procedure:

  • Click the Test button to hear the quality of your sound at a given MP3 compression setting.
  • Choose RAW under the compression menu to hear the sound without compression.
  • Click the Stop button to stop playback of the sound.
  • Click OK when finished.
Follow the above procedure for each sound in the Library window.

When you export a movie as SWF, Flash compresses all sounds according to your compression settings. This does not affect the original sound file on your hard drive. Flash makes a copy of these files, compresses them and adds them to the swf (Flash 5 file format). In addition, when you test a sound, notice that Flash takes a moment to process the sound before playback. That slight delay occurs because Flash makes a temporary copy of the sound, compresses it and then plays it. Compressing a sound does not change the original source audio file on your hard drive.

Create a Sound-Only Movie: Export the SWF
After you have finished creating sound-only movie clips and setting the compression for all the sounds in the library, you are ready to export your sound-only movie in SWF format. SWF is a compressed and compiled version of your original FLA movie. The SWF file size is usually much smaller for any given sound than wav or aiff files and is the required format for the Flash player. Follow this procedure to export the SWF file:

  • Choose Export Movie under the File Menu.
  • Browse to the folder you want to save, enter a file name for your SWF, and and click Save or OK.
  • Click OK in the Export Flash Player dialog box. Flash will show a status bar as it compesses all sounds with MP3.
You can also create an SWF with the Publish command. Publish and Export Movie commands achieve the same results. If you decide to use Publish, be sure to uncheck the HTML checkbox in the Format tab of the Publish Settings dialog box. This prevents Flash from creating an unnecessary HTML document.

Notes:
Sound-only movies have many sounds.
Each sound is contained in a sound-only movie clip.
A sound-only movie comprises multiple sound-only movie clips, each containing a sound.
Each movie clip has a unique name.
Single-click a movie clip circle to change its instance name.
Double-click a movie clip circle to access its timeline.
Click the Scene 1 button on the main stage to return to the root timeline.

Sonify Your Web Site:Adding Interactive Sound
After creating a sound-only SWF file, you can begin to code a Web page for sound. Coding with the FlashSound API typically requires four steps:

  1. Set the path to the flashsound.js JavaScript library
  2. Create a FlashSound instance.
  3. Embed your SWF.
  4. Play or stop sounds with FlashSound JavaScript API commands attached to links, buttons, or graphics.
Copy and paste the complete code template. You may find it helpful to view the template while reading through the explanation of each step.

Step 1: Set the path to the flashsound.js JavaScript library

Add a script reference to the FlashSound API JavaScript library, flashsound.js, to the head section of your Web page. This provides your Web browser with the JavaScript content needed to use the FlashSound API. You can download the flashsound.js script file from Sonify.org (Windows users right click, Mac users option click, and save from the menu). Here’s the script you need to add. Replace the pathto portion of the URL with the path to the script on your server.

         Playing with the FlashSound API  
Step 3: Embed your SWF

Embed the SWF content at the end of the HTML document just before the closing tag. To embed your SWF, add the URL of the SWF to the embedSWF() method. This embeds a 1 by 1 pixel hidden instance of the Flash Player in the document wherever you place the embedSWF( ) statement. For example:

      web page content.......     
The embedSWF( ) method is one of the special FlashSound API JavaScript commands. The method tells JavaScript that the instance named named in the method is a JavaScript container for the SWF (in the example it's called "your.swf"). Keep in mind that anytime you want to manipulate embedded SWF content with JavaScript, you must use the corresponding instance name with a FlashSound API command. Each SWF must have a FlashSound API instance and an embedSWF( ) statement.

Step 4: Create a link with onMouseover and onMouseout events

The link starts the sounds when the user moves the mouse over the link and stops the sound when the mouse leaves the link. Use the TGotoAndPlay( ) method to play sounds in your SWF.

   Hear a cool sound
The dummy href="javascript://" and the onClick="return false" attributes in the link prevent the page from unloading if a user clicks this link.

The TGotoAndPlay(targetpath, frame) method is the most common FlashSound API method for playing sounds. The method finds the specified movie clip in your embedded SWF, and then goes to the specified frame number or label and starts playing the movie clip from that point.

Clip target paths are much like URLs. For example, the URL "/products.html", indicates that the "products.html" Web page is in the root directory; the forward slash "/" means root directory. In Flash, the syntax, "/" represents the root timeline instead. So if you attach a movie clip with the instance name "coolsound" to the root timeline, the target path would be "/coolsound". This tells the Flash Player to find the movie clip with the instance name "coolsound" attached to the root timeline. For more information on target paths and slash syntax read "Understanding Slash Syntax Target Paths."

In the Creating Sound-Only Movies section of this QuickStart, you added sounds to a movie clip with frames labeled "start" and "stop." The frame labeled "start" contained your sound. When the Flash Player plays this frame the sound plays. The frame labeled "stop" contains a stop sync sound command. When Flash plays this frame your sound stops. To create interaction, you tell the Flash Player which sound to control with the target path and whether to start or stop by playing the "start" or "stop" frame.

Sonify Your Web Site: Add Backing Music
You can use the FlashSound API to add backing music to your Web site as well as interactive sound. Backing music is a great way to add ambiance and character to a site. Flash has two kinds of sound playback, stream and download. There are pros and cons to using either downloaded or streamed sounds. Be sure to consider these before deciding on a method of delivery.

  • A stream sound plays as it loads. Therefore, a user does not have to wait long to hear sound. However, the disadvantage is that bit rates of 32kbps or less, (required for steady streaming on a 56kbps modem), often produce low quality music or sound. In addition, users will experience breaks in the sound if their data transfer rate cannot keep up with the stream.
  • Downloaded sounds do not begin to play until they are fully loaded. Therefore, you should use this method only with sounds that fit into small files so that users don't have to wait too long for the sound to start. The advantage of downloaded sounds is that they don't break up over slow connections and (because there's no bandwidth limitation during playback) can be of higher quality. You can achieve a reasonable balance between sound quality and download time with higher bit rates (32kpbs or more) if your sound has a short duration (less than 5 seconds).
Autostart Download Sounds
To create an Autostart sound, change the ActionScript
Figure 16.
in frame 1 of your sound's movie clip to TGotoAndPlay("start"). This method tells Flash to jump to the start frame. Flash will wait until the sound is fully loaded, then automatically begin playingthe sound. This technique does not require JavaScript to play the sound (see Figures 15 and 16).

Play a Download Sound After Page Load
Sometimes you need to play backing music after the page layout is in place. In this case, do not use the Autostart approach because with that approach your sound may start playing before the layout is rendered. Instead, use the window.onload event to play backing music. With this technique, the browser waits until your SWF file and all the graphics and HTML on the page are fully loaded before playing the music. The following code is similar to the onMouseover code on the previous page, but in this case, you use the onLoad event handler in the body tag to trigger the TGotoAndPlay( ) method.

   
Stop Background Music
You can stop an onLoad or Autostart sound with the TGotoAndPlay("targetpath","stop") method. Specify the target path and stop frame of the movie clip containing the sound you want to stop. For example:

         Stop Background Music   
Looped Backing Music
To loop a sound in Flash, select your sound on its timeline and enter a value between 2 and 999 in the Sound Panel loop entry box. Looping a sound does not change the size of your SWF file (see Figure 17).

Sonify Your Web Site:Add Streaming Sound
Unlike download sounds, stream sounds do not require the movie clip approach. To create an Autostart stream sound, add a sound to the root timeline (on or after frame 5), add enough frames to the timeline to see the complete wave form of the sound and set the sync option to stream. Add some empty frames at the end of the timeline after your sound. An Autostart stream sound begins as soon as the Flash Player finishes buffering the stream sound (see Figure 18).

To keep things simple, I recommend placing interactive sounds and streaming sounds in different SWF files. Therefore you should have two SWF in your Web page, each with its own JavaScript instance name and embedSWF( ) statement.

Play, Stop, and Rewind Stream Sounds
The three FlashSound API commands useful for controlling stream sounds are TPlay(targetpath), TStopPlay(targetpath), and TGotoAndStop(targetpath, frame). The target path for the root timeline is "/".

Code to play a stream sound:

        Play a Stream Sound
Code to stop a stream sound:

         Stop a Stream Sound
Code to rewind a stream sound:

   Rewind a Stream Sound 
The TPlay command starts playing at frame 1 or wherever the player was last stopped. The TStopPlay command acts like a pause button. If you call the TPlay command right after TstopPlay, the Flash Player resumes playback at the pause point. Although there's no explicit rewind command, the TGotoAndStop command is well suited for rewind because it moves the Flash play head to the specified frame and stops there until you tell the Flash Player to resume playback wth TPlay or TGotoAndPlay commands.
Figure 20.

Stream Sound Guidelines
Place stream sounds only on the root timeline. A stream sound in a movie clip always downloads rather than streams. You can change the size of the Flash buffers (preloads) before starting playback. Larger buffers reduce the chance of stream interruption, but also increase the delay before playback begins. The _soundbuftime property controls the number of seconds of sound that the Flash Player stores in the buffer. Set the _soundbuftime property to the desired number of seconds to override the default buffer time of five seconds. Add your ActionScript to a frame preceding your sound (see Figures 19 and 20)

The browser caches stream files; therefore, after a stream has played through completely once, the browser will retrieve the file from the browser cache rather than request it from the Web.

The FlashSound API has many other features. For example, you can create more complex types of interactions or audio applications. Download the full documentation and explore how you can add interactive invisible sound to your Web site.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist