AS3 Avoider Game Tutorial, Part 9: Music and Sound Effects

by Michael James Williams on March 3, 2009 · 129 comments

in Articles,Avoider Game Base,Tutorial

In this part of my AS3 and Flash CS3 conversion of Frozen Haddock’s avoider game tutorial, we’ll add background music and sound effects.

Click the preview image below to see how this will look (or, rather, hear how this will sound):


If you’ve not been following the tutorial, grab the zip file of the game so far here and extract it somewhere. Otherwise, copy the files you’ve been working on so far to a new folder, as usual.

If you have been following along, you’ll probably have noticed that the graphics in this part look a little different. I realised that I’ve barely made any graphical changes to the game since Part 5, and people have been sending me these really awesome-looking versions of the game that they’ve made, so I wanted to make a few small changes. No code has been added; only the FLA has been modified. I’ve made a zip file that is identical to the one from the end of the last part, except it uses these new graphics — feel free to download it from here.

Either way, open the FLA file, and let’s get started.

Finding Music

Remember in Part 8 I mentioned 8bitrocket was a great site? Well, as further proof, check out their Music page. There are about a hundred great music loops there, all designed to work with Flash, and each one has a 11kHz preview that you can use for free (the high-quality versions only cost $10). Thanks, 8bitrocket!

For the background music of my version of the game, I’m going to use their “8bit 1″ loop (it’s near the bottom of the page). I think it fits, though it does remind me of some other song

Besides 8bitrocket, Flash Kit has some good loops, and the Newgrounds Audio Portal has some great stuff, too. Just remember to follow the licensing rules for any piece of music you want to use (and if you’re not sure, ask the creator!)

If you want to have something unique to your game, SomaTone (the team behind music for games such as Peggle, Medal of Honor: Frontline, and World of Warcraft) are getting into Flash games, so check them out if you have the money to spend.

And if none of those work for you, you can always create your own music. Just bear in mind that in this tutorial I am assuming that your music is a short piece that can loop, so if that’s not the case you may find some of it won’t apply to you.

Flash supports MP3, WAV, AIFF, and a few of the more obscure sound formats. Click here for a full list.

When you’ve got your sound file, create a new folder called Sounds inside your main game folder, and put the music in there.

Getting the Music into the Game

In order to get the music into the final SWF, we need to get the sound file into the FLA. This is simple; just click File > Import > Import to Library. Then, navigate to the Sounds folder, select your music, and hit Open.

After a few seconds, it’ll appear in your Library:


You can click that triangular play button to hear it. If you right-click the file and select Properties, you’ll get a dialog that’s a little different from the properties of a MovieClip or Button:


There’s a lot on this Window, so let’s take a quick look.

  • The first box contains the name of the symbol — just as our Avatar movieclip is named, well, Avatar. By default, this is set to the sound’s filename.
  • Below that is some basic information about the sound: its location on the hard drive, the date it was created, the audio quality, length of the sound, and size of the file.
  • To the left of that is an image of the sound’s wave representation.
  • Update tells Flash to reload the sound file from the hard drive, which is useful if you’re editing the file externally.
  • Import… allows us to swap the sound out for a different file, while keeping the other settings intact.
  • Test and Stop can be used to preview the sound.
  • Device sound, in the Export Settings section, is used if you want to specify a different sound for when your game is played on PDAs or mobile phones that use Flash Lite.
  • The Compression drop-down list, also in the Export Settings section, allows you to modify how the sound is compressed when the SWF is created — this is useful if you want to reduce the size of a very large, high-quality sound file in order to make your game load faster on the web.
  • The Linkage section is pretty much the same as for MovieClips and Buttons.

Leave the export settings as their default values, but change the name of the sound to BackgroundMusic. Also, export it for ActionScript, with a class name also of BackgroundMusic. (For now, we’re going to export it in the first frame as well.)

Playing the Music

The music is included in the SWF now (if you save and test it, you might notice that the SWF has a larger file size than it did before), but we haven’t told it to play. We’ll use code to add the music to the play screen, just as we do to add the avatar.

Open We’re going to use two objects to play the sound:

  1. The actual sound itself (i.e. BackgroundMusic, from the library).
  2. A sound channel, which controls the sound.

These should be class-level variables, so that we can control them from anywhere within the play screen, so define them near the top, with the others:

public var backgroundMusic:BackgroundMusic;
public var bgmSoundChannel:SoundChannel;	//bgm for BackGround Music

BackgroundMusic is in the library, so that’s fine, but we do need to import SoundChannel:


Let’s make the music start when the action does by putting the setup code in the constructor function:

public function AvoiderGame() 
	backgroundMusic = new BackgroundMusic();
	bgmSoundChannel =;

Line 28 initialises the sound clip from the library, just like the lines that say “avatar = new Avatar();” and “enemy = new Enemy( randomX, randomY );”. Line 29 assigns this clip to this channel, and plays it. Later on, we’ll see how to use multiple channels to handle different kinds of sound.

If you save and run the game, you may notice that the music plays once and then stops, without looping. We’ll get to this in a minute, but first let’s set the sound up with our preloader.

Things are different in CS4! If you run into trouble preloading your sounds with any version of Flash, I recommend you read this comprehensive tutorial on Activetuts+. It’s great, and it covers everything.

Much like with MovieClips, since we don’t want the background music to be a part of the preloader, we have to untick that “export in first frame” box in the Properties. (Do that now.) But, again like MovieClips, if we do this the sound won’t be a part of our SWF, and so won’t be able to play during the game. So we need to add it to the AssetHolder we made in Part 8.

Double-click the AssetHolder in the library to edit it. Now, we can just drag and drop the sound on top of the pile of stuff that’s already in there, but it makes it very hard to deal with things later. Instead, right-click Layer 1 in the timeline and select Insert Layer:


Call this layer something like BackgroundMusic (it doesn’t matter what exactly, because we never need to refer to it in code). Now, make sure this new layer is selected, and then drag and drop the BackgroundMusic from the library. You’ll notice that the keyframe in the timeline changes slightly, from this:


to this:


If you right-click any frame later on in the timeline on that layer and select Insert Frame, you’ll see why:


It’s showing a visual representation of the sound’s waveform in the timeline. Neat.

Note: Make sure you undo this change; Flash can freeze if you try to test the game while it has compiler errors and the layer with the graphical assets is only one frame long but another layer is longer. I have no idea why this is. If you make sure the layers here are all one frame long, you should be fine.

If you save and run the game and simulate a slow download, you should find that it takes a lot longer, but that the preloader’s percentage appears fairly quickly. This is great! It shows that the sound is being included in the SWF but is not forcing the player to wait until it’s downloaded before the preloader can start.

Unfortunately, you’ll also find that the music is being played as soon as the menu appears. Dang. Why is this happening before the “new BackgroundMusic()” code is being run? Well, just as when you drag a MovieClip to the stage it appears without the need for any code, when you add a Sound to the stage it starts playing without any code. It’s simple to fix though. Edit your AssetHolder, and click on any frame in the timeline that contains the sound. In the Properties panel, the following options will be visible:


All you need to do is change the Sync box to the option marked Stop:


The appearance of the waveform in the timeline will turn blank to reflect this. If you test it again, you’ll find the music doesn’t start until the game does.

Looping the Loop

So how can we make the tune play more than once? The simplest way to do it is by modifying our original code like so:

public function AvoiderGame() 
	backgroundMusic = new BackgroundMusic();
	bgmSoundChannel = 0, 10 );

Notice that line 29 has changed. That first argument, 0, tells the music to play from the beginning; if it said 30 it would start from 30 milliseconds in; 5000 would make it start from five seconds in, and so on. The second argument, 10, tells Flash how many times to loop the tune.

We could, therefore, just tell the music to loop 99,999 times, and be fairly confident that anyone playing the game will not still be playing after this time (the eight-second clip I’m using could be played continuously for nine days before reaching 99,999 loops). This is a solution, but it’s not a very flexible one.

Instead, what we can do is use an event listener (yes, another one!) to detect when the music has finished, and use an associated event handler to start it playing again. The event we need to detect is called Event.SOUND_COMPLETE, and we add the event listener to the sound channel like so:

public function AvoiderGame() 
	backgroundMusic = new BackgroundMusic();
	bgmSoundChannel =;
	bgmSoundChannel.addEventListener( Event.SOUND_COMPLETE, onBackgroundMusicFinished );

No import is needed this time, since we already imported before :)

Now for the event handler:

public function onBackgroundMusicFinished( event:Event ):void
	bgmSoundChannel =;
	bgmSoundChannel.addEventListener( Event.SOUND_COMPLETE, onBackgroundMusicFinished );

[Note we've added the event listener to the sound channel again. This is because the line "bgmSoundChannel =;" causes all event listeners on bgmSoundChannel to be lost.]

This is more flexible; for example, if we had several different pieces of music, we could play a different one each time the current one finished.

But now we have another problem. When you get game over, the music doesn’t stop — and if you click Restart, another sound channel is created, and the music is played twice at once! To solve this, we just have to tell the music to stop when the avatar hits the enemy (or whatever you’re using to trigger game over):

if ( avatarHasBeenHit )
	dispatchEvent( new AvatarEvent( AvatarEvent.DEAD ) );

Line 164 shows how to do this. It’s really simple, just call stop() on the sound channel. This won’t dispatch an Event.SOUND_COMPLETE, by the way.

Adding Sound Effects

Sound effects are just as easy to add as music clips. I’m going to make a short sound play every time a new enemy is created, as a demonstration.

The sound I’m going to use is called Synth Bleep 4. I found it on Flash Kit, and it was made by xk, which I think stands for XKrew. Thanks, xk!

Just as before, we need to:

  1. Save the file to the Sounds folder
  2. Import the file to the library
  3. Give the Sound a different name (I picked EnemyAppearSound)
  4. Export it for ActionScript but not in first frame
  5. Add it to a new layer of the AssetHolder, but set the Sync to Stop

Phew. Now for some code. First, let’s create the Sound object itself, and a new sound channel to play it. Put these with the other sound variables we’ve created:

public var backgroundMusic:BackgroundMusic;
public var bgmSoundChannel:SoundChannel;	//bgm for BackGround Music
public var enemyAppearSound:EnemyAppearSound;
public var sfxSoundChannel:SoundChannel;	//sfx for Sound FX

Also, initialise the sound in the constructor function:

public function AvoiderGame() 
	backgroundMusic = new BackgroundMusic();
	bgmSoundChannel =;
	bgmSoundChannel.addEventListener( Event.SOUND_COMPLETE, onBackgroundMusicFinished );
	enemyAppearSound = new EnemyAppearSound();

We need to make the sound actually play at the point in the code where the new enemies are being created. That’s this part in the onTick() function:

if ( Math.random() < 0.1 )
	var randomX:Number = Math.random() * 400;
	var newEnemy:Enemy = new Enemy( randomX, -15 );
	army.push( newEnemy );
	addChild( newEnemy );
	gameScore.addToValue( 10 );

Just add the line to play the sound, like so:

if ( Math.random() < 0.1 )
	var randomX:Number = Math.random() * 400;
	var newEnemy:Enemy = new Enemy( randomX, -15 );
	army.push( newEnemy );
	addChild( newEnemy );
	gameScore.addToValue( 10 );
	sfxSoundChannel =;

Save it and run it, and you’ll hear a cacophony of thumping sounds, like being near any road ever in a city at night. Awesome!

One thing to note is that the sfxSoundChannel can clearly handle playing sounds that overlap. So, why bother using two sound channels at all? Why not just have a single channel that plays all of the music and effects?

There are two main reasons. First, having the background music separate like this means we can loop it easily with that event listener/handler. Second, different sound channels can be given different levels of volume, which means we can make the music quieter and the effects louder, within the game, without having to change the volume of the individual sounds.

Going Further

Sound is really important in a game, and has a huge effect on the way it feels. There is so much you can add to a game, even with just these simple commands I’ve shown you.

If you want to take this much further, read up on the SoundChannel class, in particular the parts that explain how to use a SoundTransform.

Below are some ideas for challenges to help you to get to grips with using sounds in Flash.

A mute button. “Click here or press ‘m’ to mute.” Not too hard, just use .stop() on all playing channels. Building on this, how about separate mute buttons/keys for the music and effects? Also, can you figure out how to make the mute button pause the music, rather than making it stop and then having to start from the beginning again? (Here’s a hint: you can use bgmSoundChannel.position to find out how many milliseconds through the music you are at any given time.)

More sounds. A “ding” when the game has preloaded. A sad noise when you get game over. Different music tracks — perhaps selected at random, perhaps selected by the player. Different sound effects for different enemies. Special noises for when you get 1,000, 5,000, 10,000 (etc) points.

Playing to the beat of the game. The sound effect I’ve used could sound like part of the background music, if only the timing were right. How about making the enemies appear in time with the music? I think you’ll have to be more musically-inclined than I am to do this :)

Any other ideas? Post them in the comments!

Wrapping Up

So that’s music. Thanks again to 8bitrocket for letting me use their track. Thanks also to Flash Kit and xk for the sound effects.

As always, you can download a zip with all the files relating to this part of the tutorial here.

In the next part, we’ll add multiple levels to the game.

{ 128 comments… read them below or add one }

Michael Williams June 22, 2009 at 7:25 pm

Nice work :)

Saving the position: is it possible that msSoundChannel.stop(); is setting msSoundChannel.position to 0?

I suspect the double-music problem is due to the way event listeners work. Presumably you’ve added an event listener to the keyboard, and the handler says “if key is M then start the music again”. In Part 12 you’ll discover that the listener and handler (and even the play screen and sound channel) still linger, even after you’ve removed the play screen. It’s actually this lingering sound channel that is playing the music.

The simplest solution to this is to create a new function, say deconstruct() inside the play screen, and call it when removing the screen. Inside this function, use removeEventListener() to “clean up” any listeners that might still be hanging around.

I agree with you on the sound choices; I wrote about that here, in fact ;) Hope you get it fixed.

Matthew Ammann June 22, 2009 at 8:11 pm

Hooray! You were right about the soundChannel screwing up the positioning. All I had to do was put

pausePosition = msSoundChannel.position;

In front of my msSoundChannel.stop(). I can’t believe I couldn’t see that before! Of course it has to record the position before the channel stops the music. I’ll work on having ‘m’ as a mute button after I can get this massive bug out of my game (it’s more relevant in Part 10, so I’ll post my question there).

Michael Williams June 22, 2009 at 8:25 pm

Great! :)

Dan G June 24, 2009 at 6:36 pm

Nice work you got here.

I followed this tutorial and I’m having a problem with my game sounds increasing the size of my frame 1 which throws off my preloader. I’ve ensured all the sounds do not have “Export in frame 1″ checked. But my first frame is still about 512 KB. However if I either delete my sounds or uncheck “Export for Actionscript” then my frame 1 size is a considerable 8 KB. Any ideas?

Dan G June 24, 2009 at 8:19 pm

I figured it out.

I read Jeff Fulton’s Preloader Tutorial at 8bitRocket and noticed he’s handling sounds a little differently. I did as he did and dropped my sounds on the second frame of each layer within my assetholder and then changed the sync box from “stop” back to “event”.

That seemed to do the trick and now my frame 1 is a much smaller size and the preloader kicks in sooner.

Hope this helps someone who was having the same problem!

Michael Williams June 24, 2009 at 11:24 pm

Thanks Dan!

It’s weird, I’ve never had such a problem with this method before, but a lot of people (including you) have. I have no idea why; a newer Flash player perhaps?

Well, whatever the reason, I’m going to change this tutorial so that it uses Jeff’s original method rather than my own.

Cheers for letting me know how you fixed it :)

Lou September 6, 2009 at 3:46 pm


I’ve tried Dan G’s method, and it does reduce the first frame size but, on mine, it means that the music is playing as soon as the swf is loaded rather than when playScreen is loaded. Is there a way around this?

Michael Williams September 7, 2009 at 3:59 pm

Hey Lou,

Is the sound definitely in the second frame of the AssetHolder (not just the main FLA), and set to event?

Lou September 9, 2009 at 6:46 am

Hi Michael,

Yes, it is. Just to make sure, I’ve deleted it from the library and re-imported it and added it to the asset holder (1st frame of asset holder) which is on the second frame of the main timeline. I also deleted frame 1 on the main timeline just to make sure there were no rogue instances of it, and then inserted a new frame 1.

On simulate download, both sounds (background music & enemyAppear ‘pop’) play for one loop when the menu screen appears. And, if I start the game before the end of that first loop, you can hear two background music playing. The only place either are instantiated are in, so I don’t understand why the sound should play before playScreen is called. I wondered whether it’s to do with gotoAndStop(3), from onCompletelyDownloaded in I’m a bit flumoxed.

Michael Williams September 9, 2009 at 12:32 pm

@Lou: Ah — you said “1st frame of asset holder” but the sound needs to be on the second frame of the asset holder; could that be it or was that a typo?

Lou September 10, 2009 at 11:35 am

Yep, that was it!. And you said ‘second frame’ in the first place. Sorry about that. And thanks for your help, again.

Michael Williams September 10, 2009 at 3:04 pm

@Lou: Great! You’re welcome :)

Jonathan September 16, 2009 at 2:00 am

In the document class I have this..

public function onRequestMouseControlOff( navigationEvent:NavigationEvent ):void
    var playScreen:AvoiderGame = new AvoiderGame( mouseOn );

In the I have this..

public function AvoiderGame( shouldUseMouseControl:Boolean )
useMouseControl = shouldUseMouseControl;
//then the coding for the music like you said in this part..

The problem (I think at least).. is that when I press the keyboard button on menu screen to turn on keyboard control it runs the avoidergame function.. I hear the BGM playing.. so when I press start after pressing the keyboard button it runs the avoidergame function again which plays the music/sounds again (after one play through the keyboard button one stops though).

I dont know how to stop the music from happening when I press keyboard without stopping the music from happening after pressing start..

Jonathan September 16, 2009 at 2:21 am

lol.. well I spent like 3-4 hours trying to figure it out before posting comment.. then went to make something to eat and while I was cooking I was thinking still.. figured it out..

I just deleted

var playScreen:AvoiderGame = new AvoiderGame( mouseOn );

from the onRequestMouseControlOff because when I press start it was returning mouseOn to avoidergame already with..

public function onRequestStart( navigationEvent:NavigationEvent ):void
            playScreen = new AvoiderGame(mouseOn);
            playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
            playScreen.x = 0;
            playScreen.y = 0;

        addChild( playScreen );

        menuScreen = null;

Michael Williams September 16, 2009 at 2:06 pm

Nicely solved, Jonathan!

Rob October 13, 2009 at 2:44 pm

Hello there.
I’m in the process of picking up AS3, and your Avoider Game posts have been a huge help!
But I’m having a small problem with trying to get sounds working in my current project. I’ve followed the tutorial above and the sounds all WORK, but there’s an odd behaviour, which I’m sure has a rational explanation.
The first triggered sound plays at the the correct time (ie: exactly when it’s triggered). Subsequent sounds are then delayed.
I’ve tried everything I can think of (which admittedly isn’t much), but haven’t stumbled on a solution yet. Any idea what I might be missing?
Thanks again for the great posts!

Michael Williams October 15, 2009 at 5:28 pm

@Rob: Thanks! Hmm, that’s an odd problem that I haven’t seen before. How long is the delay? Does it get longer over time?

Rob October 16, 2009 at 8:54 am

Hello again – and thanks for the reply!
I still haven’t figured this out. The delay is about a second or so (and it’s not that they have a section of silence at the start). The delay doesn’t seem to get longer. I HAVE realised that it’s the sounds that are triggered by custom events that are playing with the delay. Sounds that are triggered directly from functions in the main class are playing instantly.
I’m presuming that if you want a sound triggered by an event in a sub-class, it’s the class where the sounds are defined that has to listen for the event and then trigger the sound. Or is there a way for sub-classes to access the sounds directly? Or is it maybe something to do with bubbling? How quickly does an event ‘bubble’? Argh!
Oh well, it’s Friday at least.

Michael Williams October 16, 2009 at 6:44 pm

Hey Rob,

Yeah, it does take a little time for events to bubble, but I don’t think this would take a whole second. Try putting a trace( "requested sound" ) in the function that fires off the effect, and a trace( "playing sound" ) in the function that actually plays the sound — you’ll be able to see where exactly the delay is, then.

Is there any silence at the *end* of your sound?

Rob November 2, 2009 at 3:39 pm

Hey there again, Michael.
I ended up saving my sound files as WAVs instead of mp3s. I think Audacity was adding snippets to the start and end. I’m still not 100% sure that’s cured it, but it seems good enough for now. Thanks for your help and sorry for wasting your time!

Michael Williams November 3, 2009 at 12:03 am

Hey Rob,

Hmm, that’s weird. Crazy Audacity. Well, glad to hear you’ve solved it, thanks for letting me know :)

Craig Lynch November 26, 2009 at 9:47 am

Hey Michael!

As always, amazing tutorials! I just had one quick question:

I’m trying to make two separate mute buttons. The BGM channel is working fine with the stop(); command, but running the same command on the SFX channel gives me a null object reference error (I assume because there’s no sound playing on the channel when I try to mute the game). So, in order to mute the SFX channel, do I just need to go to everywhere in my code that calls any sounds on the channel and add a if(SFXon==true){playsound} kind of a thing, or is there an easier way to just disable the whole channel and any commands that are run on it?

Again, thanks so much for your tutorials, I’m getting pretty close to finished with a game, and this is where I would say I’ve learned well over 50 percent of my actionscript. This is an amazing resource, and the first place I would recommend anyone trying to learn AS3.

Best regards,


Michael Williams November 27, 2009 at 6:36 pm

Thanks Craig!

Your method of using an if statement will work fine, and you could simplify it by making another function — let’s call it playSoundEffect() — that you have to call when you want to play SFX; then this function can take care of deciding whether or not to play it.

For example:

public function playSoundEffect( soundEffectName:String ):void
    if ( sfxOn == true )
        if ( soundEffectName == "enemyAppear" )
            //play enemy appear sound
        else if ( soundEffectName == "avatarGetsHit" )
            //play avatar gets hit sound

Alternatively, you could get around this by using a SoundTransform on the SFX SoundChannel. You can use one of these to mute the entire channel (so sounds will still get played, but you won’t be able to hear them).

Hope that helps, and cheers for the kind words :)

Ines December 2, 2009 at 4:40 pm

Hi, it’s me again.

This time I tried the Mute button. The problem I’m having is that it seems I’m not able to press it! I only see the ‘Over’ frame of the button for an instance when I move the avatar over it (in mouse control mode) and it goes back to its normal state immediately. It’s like every frame or tick something is making the button act like the pointer is not over it, so I never have the time to click it.

Why can this be happening?
Thanks for your awesome tutorial!

Ines December 2, 2009 at 4:45 pm

Oh, I just noticed it only happens when in Mouse control mode. If I use keyboard control, I can press the Mute button with my invisible mouse pointer.
At least I’ve been able to check that my mute button works perfectly :)

Michael Williams December 3, 2009 at 12:46 am

Hey Ines,

Sounds like the avatar is “getting in the way”; it’s blocking the mouse cursor from being able to click your mute button.

Try this: you know where you have the line

addChild( avatar );

Well, immediately after that, put the line:

addChild( muteButton );

(…assuming that’s what your mute button is called.)

What addChild() will do in this case is move the mute button so that it is on top of the avatar, so then the mute button will be in between the cursor and the avatar, instead of the other way around. Make sense? Let me know if that fixes it :)

Ines December 3, 2009 at 1:47 pm

Hey Michael,

Thanks for the suggestion, it works! Although now the button is over the avatar, so it doesn’t look as good but oh well. I don’t know if there would be a way of drawing the avatar on top of the button and then clicking “through” it.

Anyway, most games woudn’t have this problem I guess.

Jaan December 3, 2009 at 5:19 pm

Hey Micheal,

The background music sound good at the beginning( no gaps when looping), but when I added a sound effect, now there’s a little gap when background music ends and starts again(loops).
I added a sound when the game ends:

if (avatarHasBeenHit)
                gameoverSoundChannel =;
                dispatchEvent(new AvatarEvent(AvatarEvent.DEAD));

Jaan December 3, 2009 at 5:41 pm

Hey Micheal,

I have a little issue with background music looping, at the beginning, it played nicely, but when I added a sound effect, now theres a little gap between looping. Don’t know what causes it. I tried to delete the sound, but still the gap is there.

Michael Williams December 4, 2009 at 12:27 pm


You could try setting avatar.mouseEnabled = false. More info here.

Ines December 4, 2009 at 2:21 pm

That did the trick. Awesome!!

Michael Williams December 5, 2009 at 12:47 pm

Excellent :)

Michael Williams December 8, 2009 at 3:27 pm

@Jaan: Whoops, my blog thought your comment was spam for some reason! So I didn’t see it till now — sorry about that.

Not sure what’s causing this problem. It was definitely working before, with the same music?

default0 February 14, 2010 at 11:40 pm


got one damn problem with the sound.

Heres what its like:
I go to AssetHolder -> Add the Sound -> Make it stop
Result: Sound does load, but for some reason I cannot access it… (bgmChannel = would throw an error “Invalid Sound”)


p>Test results:

-Ticked “Export in first frame” -> Everything worked fine

-File Size didnt change at all, whether it was ticked or not….

Any ideas??

Best regards

default0 February 15, 2010 at 2:09 pm

The problems went to heaven without me changing a single thing…. omg, thats strange.
Flash has managed to complete my confusion o.O

Best regards

Carrot February 16, 2010 at 3:37 pm

I need help with pausing the background music with the key “M”.

I’ve tried several times without succeeding. Either the “M” key is not responsive with no errors or I get an error with the if I typed something like this into the public function of AvoiderGame in

stage.addEventListener(KeyboardEvent.KEY_DOWN, soundMute);

There might be other problems as well but I’m not that sure. I’m still new to actionscript. Thanks in advance. :)

Michael Williams February 17, 2010 at 11:21 am

@default0: Well… that’s odd, but great!

@Carrot: What errors are you getting?

Epic428 March 9, 2010 at 9:06 pm

Hey Michael, I was wondering if you knew of any good tutorials or if you had any good tutorials about using images the same way as sound files. See I have photoshop so i used it to make different images like a side panel and some in game objects like walls etc. this is for a different game im working on but using these basics for starting it off. Now I import the images to the library so that i could use them and when they are imported i get two different ones in the library. One turns out to be a Graphic Symbol while the other shows up as Bitmap Data becuase i chose to use png files. I am confused as to the difference between both of these files. As well BMD allows for export to action script while the Graphic does not which only further adds to the confusion lol. I tried adding everything to a movieclip hoping that would show the images and it would work but i had no luck. either way id like them in a movie clip so different clips are different levels. The only way i could get the images to show was if i physically placed them in the timeline which goes against everything taught in these tutorials. Any suggestions, clues, hints or ideas on using image files would be very helpful as i wont be able to move forward with out them. And thanks again for all the work you do it is wonderful.

.-= Epic428´s last blog: Fast..Faster..Fastest Fox =-.

Epic428 March 9, 2010 at 10:10 pm

lol scratch that last comment because i realized the reason nothing was ever showing up when compiling was due to the fact that i never told flash where to find the classes. so it wasn’t loading anything. i realized this when i tried editing the document class from the fla file and it said it didn’t know where it was. so after correcting that and commenting out about 400 other lines of code i was able to test that the images would show up the way id like them to and they did :)

.-= Epic428´s last blog: Simple Windows Keyboard Shortcuts =-.

Adridle March 15, 2010 at 10:58 pm

Hi Michael, It’s me again asking for a little of your time.

I’m having a weird issue using sounds. You see, I’m trying to do a small beat’em up game, and everytime the player hits an enemy, a sound must be triggered. So It does it right when I hit an enemy, the problem appears when I hit more than one enemy at once. The first enemy hit sounds right, but the second always has a 1 second delay; the weird stuff is that after that second delayed sound all the other hits sound just at the right time.

What could I be doing wrong? Heeelp! T_T

Thanks in advance =D

Michael Williams March 20, 2010 at 11:50 am

@Epic428: Oh, OK, heh ;)

@Adridle: Very odd. Uhm… do you get any errors?

Adridle March 22, 2010 at 3:53 am

No, everything is just fine. No errors, no warnings =(
I tried the swf on a Mac G5 and the sound problem disappeared (but the game ran a little slower). So I returned to my PC and the issue was still there. I checked it again on the G5 and the sound problem reappeared =S

Whats going on? T_T What am I doing wrong? Were could I start tracing the issue?

Michael Williams March 22, 2010 at 11:02 am

Hmm. OK, you need to isolate whatever code is different when you hit two enemies at once. Any ideas?

Adridle April 15, 2010 at 7:55 am

OMG! I’m so sorry! I clicked on “Notify me of followup comments” and was waiting for the response, but since the e-mail never arrived I thought the topic was forgotten. I’m really sorry.
I ignored the issue and kept working on the game. When I added the Music the issue solved itself.
I really appreciate the help, thanks a lot!

Keep up the good work! You really help us with this web page.

Best Regards

Michael Williams April 23, 2010 at 1:01 pm

No worries, Adridle.

Well, glad it mysteriously sorted itself out :) Thanks for the kind words.

Tiziano April 30, 2010 at 8:17 pm

Great, I’ve completed your tutorial using only free stuff! At the moment anyway I’ve got a couple of problems: when adding the event listener to:

bgmSoundChannel.addEventListener( Event.SOUND_COMPLETE, onBackgroundMusicFinished );

i got the error:

Call to a possibly undefined method addEventListener through a reference with static type BackgroundMusic.

while BackgroundMusic is not static at all. Anyway I’ve used the Class Sound to embed the music inside FlashDevelop, like this:

[Embed(source = '../sound/backgroundMusic.mp3')]
static private var BackgroundMusic:Class;
static private var bgMusic:Sound;

what is this error about?

Anyway, here is the result so far. Since I don’t like avoider game, I’ve add the possibility to shoot, just one shoot at a time :)

Michael Williams May 7, 2010 at 8:02 pm

Congrats, Tiziano!

That error just means that the BackgroundMusic class does not have a function called addEventListener(). The “static” means something different here than how we’ve used that word in the past: it means you can’t just add new properties and methods to the class at runtime. (Don’t worry about this for now.)

My guess is that your BackgroundMusic class doesn’t extend something that can dispatch events. What does it extend?

Ha, your game is cool! I like it being fast like that. Feel frantic. I scored 2390 :)

Tiziano May 11, 2010 at 3:53 pm

ehmm… BackgroundMusic didn’t extend anything… my fault!
Now it works, thanks!

By the way, I’ve modified my game: added lives, bonus and transformed in something mush less frenzy. Next step: add boss.
(and solve bugs, and put buttons for mute sounds and effects, and….)

Michael Williams May 16, 2010 at 1:47 pm

Oh wow, that’s really cool! I love the way the “extra life” letters animate in smoothly. And I see a couple new enemies — or were they there before?

I got a score of 5540 this time.

Ooh the bomb is a nice idea, too :)

invasion May 30, 2010 at 3:33 am

Nice tutorial, but I found this page while searching for a solution to the 1 second sound delay that Rob was experiencing. I used soundbooth to trim any silence at the beginning but I think my problem may be caused by wav files. I try mp3′s…

Leave a Comment

Writing code? Write <pre> at the start and </pre> at the end to keep it looking neat.

Anti-Spam Protection by WP-SpamFree

{ 1 trackback }

Previous post:

Next post: