Tutorial – Using Sound in ActionScript 3

Author : Craig

Author's Website | Articles from

This 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:


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:

code

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):

stop button

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):

code

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:

code

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:

code

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:codeNotice 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:

Like this post? Share it!

  • Tweet
  • Facebook
  • Diggit
  • Delicious
  • Diggit
  • Diggit
  • Diggit
  • Diggit
  • Diggit

Related Posts


User Comments


  1. Faaric Sameem
    March 26, 2008

    Hi, Thanks for the tutorial its great.

    But how would I approach this If i was to have the music file in the library?

    Reply

  2. Angel Romero
    March 27, 2008

    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.

    Reply

  3. kiki
    April 10, 2008

    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?

    Reply

  4. deepankar
    April 17, 2008

    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??

    Reply

  5. Fritz
    April 22, 2008

    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

    Reply

  6. Fan
    April 26, 2008

    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..>>?

    Reply

  7. Nik Rowell
    April 30, 2008

    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 ;)

    Reply

  8. Em
    May 30, 2008

    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.

    Reply

  9. phil
    June 20, 2008

    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

    Reply

  10. harry cutts
    August 2, 2008

    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

    Reply

  11. harry cutts
    August 2, 2008

    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

    Reply

  12. brianp
    August 6, 2008

    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.

    Reply

  13. Dewet
    August 17, 2008

    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.

    Reply

  14. Scott
    August 22, 2008

    The music play as soon as i open the file. Is there any way i can stop this?

    Reply

  15. Kamen
    September 6, 2008

    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.

    Reply

  16. Wes
    September 15, 2008

    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.

    Reply

  17. Lisa
    September 30, 2008

    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.

    Reply

  18. misty
    October 10, 2008

    How do I get this to work so that the music plays automatically on load rather than having to press the play button?

    Reply

  19. nudlefry
    November 9, 2008

    Nice one! I have just one question: How can i stream music files with XML?

    Reply

  20. MarlJP
    November 20, 2008

    Thanks! You explain this very well and thoroughly!

    Reply

  21. Abhay
    January 3, 2009

    Thanks bro. it helped me………

    Reply

  22. Ian
    January 9, 2009

    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.

    Reply

  23. bianca
    February 1, 2009

    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

    Reply

  24. bianca
    February 1, 2009

    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?

    Reply

  25. hannsaki
    February 14, 2009

    thanks for this useful tutorial~^^

    Reply

  26. Kei
    March 24, 2009

    This is a great tutorial! Now I can create my own player.
    Thank you very much.

    Reply

  27. Sean
    March 24, 2009

    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;
    }
    }

    Reply

  28. Sean
    March 24, 2009

    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?

    Reply

  29. kaubatak
    March 25, 2009

    Thx for this tutorial!!!Great!!!

    Reply

  30. Antony
    April 14, 2009

    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

    Reply

  31. MDT
    April 20, 2009

    Can you use an AIF file instead of a MP3? If so, what do you have to change in the code?

    Reply

  32. Graphic Designer
    April 28, 2009

    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…

    Reply

  33. Jenny
    May 6, 2009

    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.

    Reply

  34. Gia
    May 17, 2009

    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)

    Reply

  35. Mike
    May 20, 2009

    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.

    Reply

  36. Kiara Gilbert
    May 29, 2009

    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?

    Reply

  37. Panagiotis Kosmidis
    June 2, 2009

    Hello, nice tutorial but what about wav files? How can we load wav file?

    Reply

  38. Luis Puche
    August 11, 2009

    Hi to those asking how to loop and about that stream error do this:

    Loop:
    Replace every
    sc = music.play(pos)
    with
    sc = music.play(pos,99)

    The ones with the error have to drop the music file in the place where the index is, it fixed my problem

    Reply

  39. Angie
    August 15, 2009

    Nice. In AS3, how can I adapt this to work with a streaming FLV that is being loaded with the FLV Playback component? (versus having to use the VolumeBar component).

    Reply

  40. Dustin
    August 31, 2009

    Hey man, this is fantastic, got my sound working for my game in no time!

    Reply

  41. Long Sim
    September 17, 2009

    Hey come on let us copy and paste the code!

    Reply

  42. Chris Bare
    September 20, 2009

    Great tut. Worked without a problem. However, I am interested in playing more then one file? With two buttons to skip to the next track ” “.

    Reply

  43. Atrix256
    September 27, 2009

    Great article! Thanks for showing how to do that.

    Bug report: if you press stop before pressing play, it throws an error. Just FYI, still great tutorial (:

    Reply

  44. ninja
    December 31, 2009

    I loved the tutorial!
    Very easy to understand for a simpleton like me! :)

    Reply

  45. Muby
    February 23, 2010

    Thanks You ! appreciate to get source !!

    Reply

  46. Endpoint
    March 18, 2010

    You are GOD!!!!!!!!!!! Thanks for this article, i hope you do the next button as well….

    Reply

  47. GregJW
    March 19, 2010

    Regarding loops;

    sc = music.play(pos,99)
    I get an error when I use this – 1020: Access of undefined property

    I was able to fix this by using
    sc = music.play(0,99)

    but there is a skip in the loop. Is there anyway to avoid this gap in the loop?

    Here is my code:

    var music:Sound = new Sound(new URLRequest(“love.mp3″));
    var sc:SoundChannel = music.play(0, 99);
    var isPlaying:Boolean = true;

    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(0, 99);
    isPlaying = true;
    }
    }

    Reply

  48. Kux
    April 6, 2010

    When I press the stop_btn, the music keeps on playing.
    How do you resolve that?

    Also, it would be nice to show how would you use the same one button (play and stop), instead of having two buttons on stage.

    Thank you

    Reply

  49. Anu
    April 7, 2010

    Hi,

    I followed the tutorial, there’s one problem:
    If you have listened to the music, and want to restart it, you first have to push the stop-button. Simply pushing the start-button doesn’t work.
    I think that will confuse visitors of my site.
    Anyone a suggestion?
    Here’s the url: http://www.sonasi.nl/index2.html
    thanks!

    Reply

  50. Tom
    April 13, 2010

    sure, the IF statement is the most elegant solution. But another way of implementation would be just to always call the “stop music” function right before the “play” function. In that case, if any music is playing already, that would first be stopped and then the “new” music would start. The end result would be the same: just one music channel playing

    Reply

Leave a Reply

 
  Twitter Followers

Stock Flash Files Web Development Tutorials

Stock Graphics Video Files


Your Ad Here