Tutorial - Using Sound in ActionScript 3
Flash Tutorial March 24th, 2008This tutorial is Part 1 of a series of tutorials on creating a music player. Click the links below to view the other posts in the series:
- Part 2 - Creating a Volume Slider
- Part 3 - Creating a Pause Button
- Part 4 - Creating a Mute Toggle Button
Lately it seems that everyone has become somewhat of a music snob. Everyone is convinced that his or her taste in music is perfectly objective and that anyone who doesn't like his or her favorite band is intellectually inferior. For instance, if you were to tell me that you didn't adore The Shins, Led Zeppelin, and/or Billy Joel, I would probably write your mother a letter, verbally assaulting her for drinking so much vodka while she was pregnant.
Anyways, in an era where melodic snobbishness is so prevalent, everyone with a website (or a MySpace account) wants to play their favorites for the whole world to hear, so if you're a Flash designer/developer, it might do you some good to learn how to import, play, and modify sound in ActionScript.In this tutorial, I'm going to introduce you to using sound in ActionScript 3, and in later posts, we'll start to get a little more in depth with the different things we can do with sound.
Note: If you're easily bored with tutorials and just want to look at some ActionScript, be sure to check out my recent post on an ActionScript 3 / XML Music Player I created. This post contains a link to an FLA that might have some of the ActionScript you're looking for.
In this tutorial, we're not going to talk about importing a sound into Flash. Rather, we're going to discuss accessing external sound files using ActionScript without ever actually importing them into the Flash authoring environment.1. Save your Flash file. Before we do anything else, we need to save our Flash file, because we'll soon be pointing to an external sound file, and in order to point to the right location for the sound file, Flash will need to know where the FLA file will be saved as well. In this example, I'll be saving my FLA file in the same directory as my mp3 music file.2. Create a Sound Object. So far, all we're trying to do is to get a sound file to play, so we don't really need to worry about putting anything on the stage. Instead, simply select "Layer 1" on your timeline, rename the layer "Actions", click on frame 1 of this layer, and hit Option+F9 (or just F9 on PC) to open up your Actions panel for this frame. The code for creating a new sound object is simple:

To create a sound object, we first created a variable called "music" and we set this variable equal to a new Sound object. Inside the parentheses for this new Sound object, we placed a new URLRequest object, which allows us to access the URL of an external file, as we see in line 1. This external file is the mp3 file we will be playing.In line 2, we point to our new sound object and tell it to play. And with only two lines of code, we're already playing music in our Flash file!
Phase Two: Shut that Racket Off!
<rant>The only thing I hate worse than someone who doesn't like The Shins is someone who insists on blaring their own infernal music on their website without giving me the option of turning it off. In fact, if I were you, I wouldn't even play the music by default unless you're building a website for a band, or some other website where the user might expect to hear default music. But one thing's for sure--if you set up your music to play by default, you WILL lose some traffic to your site. Think about it: if you're listening to The Shins on iTunes and you come across somebody's website, which is blaring The Carpenters at 200% volume, you're probably going to hit the back arrow faster than a Yahoo Games addict when his boss is walking by. Even if you provide controls to turn the music off, many people aren't going to take the time to look for the stop button. They're just going to leave.</rant>Create a stop button. It doesn't matter what the stop button looks like, as long as it looks like a stop button. So create a new layer, draw your graphics, and then convert to a button symbol by hitting F8. Here's what my stop button looks like (in true, glossified, Web Two-Dot-Oh fashion):

I've also given my button an Instance Name of stop_btn. Here's the code that causes our stop button to work (hang on to your seats, this one's complicated):

The first thing you should notice is that line 2 has changed a little. Unlike with ActionScript 2, in AS3, you can't control the playback, volume, etc. of a sound object using the Sound class. Instead, you have to assign the playback of your sound to a new instance of the SoundChannel class. And then, using your new SoundChannel object (which we simply called "sc"), you can tell your sound how to behave.In line 4, we created the typical event listener for our button so that when we CLICK on our stop button, it will trigger the "stopMusic" function, which contains the code for stopping the playback of our music.On line 8, inside the aforementioned "stopMusic" function, notice that the "stop()" method is attached to the SoundChannel object we created, which we called "sc." And now, if we test our file, we'll see that we have the ability to stop our sound.
So, How About a 'Play' Button?
Now that we've stopped the sound, how do start it back up again?EASY! Create your play button (I'm giving mine an Instance Name of "play_btn") and add the following code to your Actions layer:

At least that's the code you'd THINK you might add! And if your user presses the right buttons at the right time, everything will be dandy! But try testing your movie and pressing the play button after the movie has already started playing, and you'll discover that you've got the same sound playing on top of itself. And the only thing worse than The Carpenters playing on someone's website is The Carpenters playing on top of The Carpenters.So before we tell our music to start playing again, we need to make sure it isn't already playing. And we're going to do this by creating a variable to keep track of our status. Let's call our variable "isPlaying" and set it to a data type of Boolean (true/false). Here's what your code will look like:

On line 3, we created our variable and set it equal to "true" since our music is playing by default. Then, inside the stopMusic function, we set our variable to false.Inside the playMusic function, instead of just allowing the music to start playing any time we hit the play button, we included an "if" statement that first checks to see if the music is already playing, and if it's NOT playing already (the exclamation point basically means "not"), then we allow it to play, and we set our "isPlaying" variable back to true.Now our music player functions beautifully!
One Last Thing
Remember earlier, when I mentioned that it's generally a bad idea to have your music playing by default when the page loads? Yeah, well I meant it! So let's talk about how we can set this up.Actually, you've probably already figured this part out for yourself. Remember that "music.play()" statement in line 2? Get rid of it! Wait until the user actually clicks on the play button before you start playing the music. Of course that also means you need to set the "isPlaying" variable to "false" in line 3.Here's your final code:
Notice that in line 2, we still declared our "sc" variable and strict-typed it to SoundChannel, even though we didn't set it equal to anything. The reason for this is that if we try to declare our "sc" variable inside the "playMusic" function, then that variable won't be accessible outside of the function. By declaring the variable outside of the function, we're ensuring that it will be available anywhere within our code.Anyways, those are the basics of creating a simple music player. As time permits, I'll be adding more tutorials that explain how to create a "pause" button and a volume slider. Until then, keep practicing!
Source files: sound.zip
Click the links below to view the other posts in the series:








March 26th, 2008 at 7:46 pm
Hi, Thanks for the tutorial its great.
But how would I approach this If i was to have the music file in the library?
March 27th, 2008 at 3:47 am
Once again nice tutorial, I really appreciate the time you take on each of your tutorials. Each process is broken down really well. Nice job.
March 29th, 2008 at 3:00 pm
[...] Tutorial - Using Sound in ActionScript 3 [...]
April 2nd, 2008 at 7:57 pm
[...] Tutorial Source [...]
April 2nd, 2008 at 9:44 pm
[...] Tutorial - Using Sound in ActionScript 3 [...]
April 10th, 2008 at 6:01 am
I have a question.
How many sound files can i play at the same time?
I am hoping to play about 16 sound files at the same time.
Do you know if that is possible?
April 17th, 2008 at 3:09 am
Great tuorial…..but i have two questions—-
1)when i press the stop button ,i get the error message”TypeError: Error #1009: Cannot access a property or method of a null object reference.
at sound_fla::MainTimeline/stopMusic()
2)how can i know how much the song is in progress??
April 22nd, 2008 at 2:52 pm
Hi Craig
Great info throughout! In the example above, how do you define it with one button used as a toggle to simply turn sound off and on?
Thanks
April 22nd, 2008 at 5:28 pm
[...] Tutorial - Using Sound in ActionScript 3 [...]
April 26th, 2008 at 8:52 am
Uh… I tried to make it so it plays automatically.. but with the stop and play button… It still seems to just duplicate the “play” so the song runs multiple times overlapping. Rather than following the IF rule. Basically… the code before you add the “One Last Thing” I’m guessing… There’s no way I can make it run automatically without it crashing..>>?
April 30th, 2008 at 12:19 pm
Nice tutorial Craig!
(I’ve probably lost a few visitors to my site because of my no-controls ambient music. The next version will be more thorough
May 30th, 2008 at 11:44 am
I couldn’t get the sound file to work at all. I even downloaded it (walk). What did i do wrong? Also, do you need someone to edit your website to make sure the text is correct and there are no typoes? If so, go to http://www.wordszilla.com. Thanks.
June 20th, 2008 at 9:19 pm
most appreciated… lookin for more like this… with the only one button that changes when clicked on to a stop button, takin up less space
June 24th, 2008 at 7:50 am
[...] came this great tutorial from School of Flash, which teaches you how to prepare the code for play/stop/pause/mute, complete with volume slider as [...]
August 2nd, 2008 at 9:19 am
Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
i get this when i try to test the movie
Musicplayer_fla::MainTimeline/Musicplayer_fla::frame1()
ArgumentError: Error #2068: Invalid sound.
at flash.media::Sound/play()
at Musicplayer_fla::MainTimeline/playMusic()
and then that when i click the play button
August 2nd, 2008 at 9:37 am
Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error. at Musicplayer_fla::MainTimeline/Musicplayer_fla::frame1()
sorry thats the first error message
(take that line off the second one
August 6th, 2008 at 7:10 am
hi there.
ive been attempting this and from what i can see i have everything worded identically except for the button names in the project im working on.
however it still wont work.
the message i get is
1120: Access of undefined property mus_sc_play_btn.
August 17th, 2008 at 1:31 am
Excellent stuff! Breaking it down into conversational language has made this a very effective tutorial.
One question: how I fade the sound in or out when the buttons are clicked? Would love to see something on that.
August 22nd, 2008 at 2:27 pm
The music play as soon as i open the file. Is there any way i can stop this?
September 6th, 2008 at 3:55 pm
Hello, I was wondering how can I loop my sample, meanining when it gets to the end it doesn’t start playing again…and some one might have actually liked it. So I’m pretty new to flash so please excuse me for that question, but I would appreciate some advice.
September 15th, 2008 at 11:49 am
Hello, I have followed all of the steps described above. Everything works fine when I test but when i put the file live on my website the music will not play. Please advise.
September 30th, 2008 at 8:34 pm
Hello!
Great tutorial! I’ve been looking for this!
One question: How do I code it to auto start first and then let the visitor decide whether he wants to stop music.
Will appreciate your help.
October 10th, 2008 at 8:13 am
How do I get this to work so that the music plays automatically on load rather than having to press the play button?
November 9th, 2008 at 1:31 am
Nice one! I have just one question: How can i stream music files with XML?
November 20th, 2008 at 2:47 pm
Thanks! You explain this very well and thoroughly!
January 3rd, 2009 at 5:44 am
Thanks bro. it helped me………
January 9th, 2009 at 6:14 pm
An unhandled flash error somewhere on this page causes Firefox for OSX to crash entirely, whether the error is dismissed or continued on. The error is triggered when I try to close this tab.
Just thought you might like to know. It’s preventing me from leaving this page without crashing.
February 1st, 2009 at 5:46 pm
Hello,
I started putting in your coding and when i tested my file an error came up asking for a definition for the sc.stop(); Is there a place where its defined that I missed? Please help… I looked briefly through the rest of your coding that this comes up a few more times so I hope I can figure this out.
thanks
February 1st, 2009 at 5:52 pm
Hey,
SOrry I realized I forgot to add the coding on line 2 to define the sc. I fixed that and tested movie and this is the error I got.
Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
at oa_index_mp3test_fla::MainTimeline/frame6()
Is this because my website is not published yet? Or in the ftp I need my mp3 to be in the same folder as my pages?
February 14th, 2009 at 5:42 am
thanks for this useful tutorial~^^
March 24th, 2009 at 1:03 am
This is a great tutorial! Now I can create my own player.
Thank you very much.
March 24th, 2009 at 12:27 pm
I’m getting compiler error codes on line 7 and 15 that say ‘{’expected. These are the only errors I’m getting. Can someone help?
var music:Sound = new Sound(new URLRequest(”http://www.cardboardsangria.com/01%20Flood%20Insurance.mp3″));
var sc:SoundChannel;
var isPlaying:Boolean = false;
stop_btn.addEventListener(MouseEvent.CLICK, stopMusic);
function stopMusic(e:Event):void
{
sc.stop();
isPlaying = false;
}
play_btn.addEventListener(MouseEvent.CLICK, playMusic);
function playMusic(e:Event):void
{
if (!isPlaying)
{
sc = music.play();
isPlaying = true;
}
}
March 24th, 2009 at 12:32 pm
I’m wondering if it can’t figure out my buttons? I have an “ACTIONS” layer (which ONLY contains the code above) and then a layer on top “Layer 8″ that has the two play_btn and stop_btn on there. Is this why?
March 25th, 2009 at 5:06 am
Thx for this tutorial!!!Great!!!
April 14th, 2009 at 5:52 pm
At last, someone who can actually articulate what to do. After reading so many confusing posts, this was really clear!!!
Thanks,
Antony.
http://www.holistickid.com
April 20th, 2009 at 7:41 am
Can you use an AIF file instead of a MP3? If so, what do you have to change in the code?
April 28th, 2009 at 2:56 am
Hi, I have followed all of the steps described above. Everything works fine when I test but when i put the file live on my website the music will not play. I have embedded music normally and this works. Any help would be really appreciated…
May 6th, 2009 at 8:09 pm
I got the same output error many of you did and when I moved my mp3 to the same folder as the swf file I was working in, the audio worked. Good luck.
May 17th, 2009 at 9:29 am
This is one of the best tutorials I have ever seen. Very good explanation of things! I have learned more of your tutorials than of our teachers. Cheers for that and keep the good work up! (And I love your taste of music lol)
May 20th, 2009 at 5:22 am
hmm it doens’t seem to work, not even the zip-file itself when I publish it.
stick to the code/explanation and don’t try to be funny all the time please.
May 29th, 2009 at 1:50 pm
Thank you so much for these tutorials! They’ve really helped me learn Flash. I just wish you had tutorials for Previous and Next buttons, as well as adding the playlist with a scroll bar so people can browse the playlist. Maybe when you’ve got some free time?
June 2nd, 2009 at 7:01 am
Hello, nice tutorial but what about wav files? How can we load wav file?