Monday, 22 September 2008

Play sound dynamically

In this tutorial you will learn how to play a sound dynamically in Actionscript 2. The audio file will be played directly from your hard drive, instead of loading from the library. If you don't want to play a sound dynamically take look at the: create a sound button tutorial.  You will need to make sure the audio file is in the same directory or folder as your FLA file, or the audio will not play. I have used free stock music which is available at:

UPDATE: Actionscript 3.0 version available here.

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() {
off_btn.onPress = function() {

**The code creates a new instance of the Sound class. The load method loads or streams an audio file. The load method has two optional parameters: true or false. The true parameter turns on streaming which means the sounds play while they are still downloading. This is useful if you have a large audio file that you want to play straight away. The false parameter turns off streaming which means the sounds will not play until its fully loaded. 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("", 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.


nowheretohide 3 September 2009 18:13  


I used this code and it is working properly until one point.

The play and stop buttons r in side a movie clip, and from this point it s not working.

Do you have any idea how should i solve this problem?



iliketo 4 September 2009 04:39  


Have you changed the code from above?

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP