Monday, 22 September 2008

Play sound dynamically

This Flash tutorial will teach you how to play sound dynamically. This means you can play an audio file directly from your hard drive, instead of loading it from the library. This tutorial is very similar to the create a sound button tutorial, but uses the loadsound() method.

Make sure your audio file is in the same folder/directory as your .fla file or your audio file will not play. I have used free stock music which is available at: www.sounddogs.com

Play sound – Dynamically

Step 1

Open a new Flash document. Create two basic buttons on the stage: one for on and one for off. For more information on buttons, checkout the basic buttons tutorial. I have created two basic square buttons, but you can create whatever you wish.



Now convert your buttons into symbols by pressing F8. Give your symbols an appropriate name, check button and click ok.


Step 2

Give your two buttons the instance names: on_btn and off_btn respectively.




Step 3

On the timeline insert a new layer called “Actions”. Right click on the first frame of that layer and select actions. And add the following code:

var my_sound:Sound = new Sound();
my_sound.loadSound("yourfilename.mp3", false);

on_btn.onPress = function() {
my_sound.start();
};
off_btn.onPress = function() {
my_sound.stop();
};


**The first line of code creates a new sound object. And the load method load/streams an audio file. There can be two parameters true or false. The true parameter is used if you are loading a large file that starts playing straight away. And the false parameter is used if you are using a small file. The start and stop functions basically start and stop the sound.

You replace the “youfilename.mp3” with the name of your audio file. Make sure your audio file is in the same directory as your .fla file. You can also load sound from a web address for example:

my_sound.loadSound("http://www.example.com/sound/ yourfilename.mp3", true);


Step 4

Test your movie clip ctrl + enter.



You should now be able to load sound dynamically. Feel free to contact me for any questions or comments.

0 comments:

Post a Comment

Welcome to ilike2flash! If you like this post you can subscribe here to get updates via RSS or opt to have them sent directly to your inbox .

I appreciate your feedback, so please feel free to comment.