Tutorial - Using Sound in ActionScript 3

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!

This movie requires Flash Player 8

Source files: sound.zip


Click the links below to view the other posts in the series:

Tags: , , , ,


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

14 Responses to “Tutorial - Using Sound in ActionScript 3”

  1. Faaric Sameem Says:

    Hi, Thanks for the tutorial its great.

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

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

  3. […] Tutorial - Using Sound in ActionScript 3 […]

  4. […] Tutorial Source […]

  5. […] Tutorial - Using Sound in ActionScript 3 […]

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

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

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

  9. […] Tutorial - Using Sound in ActionScript 3 […]

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

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

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

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

  14. […] 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 […]

Leave a Reply