Flash Script – Call Sounds Dynamically
Download the sample files here.
Imagine you have a Flash application that allows the user to select 50 different songs. If you store 50 different song files wiht the application, the file size of the project will be huge.
How can we avoid this? We’ll create 50 swf files, each containing a different song. We’ll call the file dynamically, according to the user’s choice of song.
Sound difficult? It’s not! Let’s get started! Note that this tutorial assumes that you’ve already imported a sound file into Flash.
1. Create a new Flash movie, and on its first frame, add the following script:
function mysound (flag)
{
mysound = new Sound(this);
mysound.stop();
//test is id of the sound file
mysound.attachSound("test");
//if true play
if(flag){mysound.start();}
//if false stop
if(!flag){mysound.stop();}
}
2. Open the library panel and right click the sound file. Go to "linkage properties", and select the radio button that reads "Export this symbol". Give the symbol an id name in the identifier field.
3. Now drag the sound file on to the stage from the library.
4. Select the sound layer and go to "Sound" panel as shown below. Apply the settings shown here.
5. Save the movie you as "sound.fla", and publish the movie swf only.
6. Open a new flash movie, and create two buttons as shown above. Label the first one "play sound", and the second "stop sound".
8. Create a blank movie clip. Give it an instance name of "snd".
9. In the first frame, insert the action:
loadMovie("sound.swf","/snd");
10. Right click the "play sound" button and insert the action:
on (release) { _root.snd.mysound(true);}
11. Right click the "stop sound" button and insert the action:
on (release) { _root.snd.mysound(false);}
You’re done! Play the movie!
Using this technique, you can call as many sound files as you want.