Search code examples
actionscript-3flash-cs6

ActionScript 3.0 sound not working


So having trouble making sound on keyboard press

I have the imports:

import flash.net.URLRequest;
import flash.media.Sound;

I have the variables

private var soundDownRequest:URLRequest = new URLRequest ("SoundDown.mp3");
private var downSound:Sound = new Sound (soundDownRequest);

and the event listener

private function keyDownHandler(evt:KeyboardEvent):void
    {

            if (evt.keyCode == 40)//ascii for down arrow 
            {
                downSound.play();

            }
    }

The sound folder is in the same folder as the .as, its also in the library of the fla, yet it still doesn't work. Any idea why?

Thank you.

Update:

I got the sound to work but not using the external method I was trying to do above.

Had to do it internally.

so you need:

import flash.media.SoundChannel;

-Then you need to make sure your sound file is in your fla library.

once its in the library

-Right click > properties

-Select the Action Script Tab

-Check "export for action script"

-Give the class a name in accordance to the sound

-press ok

add this variable (your will be different):

private var downSound:TheDownSound = new TheDownSound();

downsound is the selected name of the variable, and TheDownSound is the name of the class (the one made earlier for the sound file)

then add this to where you want the sound to play:

var myDownSound:SoundChannel = downSound.play();

Do this if you cant get it working externally like me.

for a better explanation watch this guys youtube video: https://www.youtube.com/watch?v=SZpwppe7yGs


Solution

  • Your code is working perfectly ok if you put your .mp3 file in the same folder as the output .swf, not near the class .as source file (because its the swf file loading the sound, so the path must be relative to it)

    public class ASEntryPoint extends Sprite {
    
        private var soundDownRequest:URLRequest = new URLRequest ("click.mp3");
        private var downSound:Sound = new Sound (soundDownRequest);
    
        public function ASEntryPoint() {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
        }
    
    
        private function keyDownHandler(evt:KeyboardEvent):void{
            if (evt.keyCode == 40) {                
                downSound.play();
            }
        }
    }