0
votes

I'm trying to play sound in as3 code using an external mp3 file.

So here's the code I am using:

    private function playSound():void
    {
        trace("loading sound");
        var mySound:Sound = new Sound();
        mySound.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
        mySound.load(new URLRequest("Menu.mp3"));
        mySound.play();
        trace("playing sound");
    }

    private function handleIOError(evt:IOErrorEvent):void
    {
        //handle error if needed
    }

The music just doesn't play at all.

The traces "loading sound" and "playing sound" appear so the code is being run.

The mp3 file Menu.mp3 is in the same folder as the .fla file used to run the project. Is this the correct directory? I tried moving it around but still couldnt play the sound.

Any help will be appreciated, thanks!

1
Your code seemed to work for me. Can you try trace( mySound.play() );? That should return a SoundChannel object, but it might be null if there is a problem with your sound card.David Mear
trace( mySound.play() ); output this - [object SoundChannel]. Hm not sure what the problem is then, so an mp3 was actually playing for you with that code?UltraViolent
Yup, I just copied your playSound() code to the timeline as a quick test, and it played an mp3 okay. I have heard of Flash having trouble with high bitrate mp3s though, do any errors show up if you try importing the file to the library?David Mear
Could you give your Main.mp3, I also checked your code - it works!Serge Him
Sure, here's a link you can download the mp3 from - picosong.com/3TyCUltraViolent

1 Answers

1
votes

I have a few suggestions that might help:

  1. Declare mySound as a class level property. The garbage collector might be disposing of the variable prematurely since it is local.

  2. mySound.play() returns a SoundChannel object. Try storing this in a class level property.

  3. Add an event listener to the sound for Event.COMPLETE, right before loading the sound. Try playing the sound after this event occurs. As it is, you might be trying to play the sound before it has loaded.

    private var mySound:Sound;
    private var mySoundChannel:SoundChannel;

    private function playSound():void
    {
        mySound = new Sound();
        mySound.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
        mySound.addEventListener(Event.COMPLETE, handleLoadCompletion);
        mySound.load(new URLRequest("Menu.mp3"));
    }

    private function handleLoadCompletion(evt:Event):void
    {
        mySoundChannel = mySound.play();
    }

    private function handleIOError(evt:IOErrorEvent):void
    {
        //handle error if needed
    }

Edit:
After reviewing the docs, I think that suggestion 3 isn't necessary.