AS2 → AS3: Loading & Playing External Sounds
Loading and playing external sounds in AS3 is not far off from its AS2 counterpart. The code, as usual in AS3, is a little different because of the new event model, but really boils down to the same thing.
Let's take a look at the AS2 version:
-
var s:Sound = new Sound();
-
-
s.onLoad = function():Void
-
{
-
trace("Song loaded.");
-
};
-
-
s.onSoundComplete = function():Void
-
{
-
trace("Song done.");
-
};
-
-
s.loadSound("music.mp3", true);
And here is how to do that in AS3:
-
var s:Sound = new Sound(new URLRequest("music.mp3"));
-
s.addEventListener(Event.COMPLETE, doLoadComplete);
-
-
var channel:SoundChannel = new SoundChannel();
-
channel = s.play();
-
channel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete);
-
-
function doLoadComplete($evt:Event):void
-
{
-
trace("Song loaded.");
-
}
-
-
function doSoundComplete($evt:Event):void
-
{
-
trace("Song done.");
-
}
As you may have noticed, there is a strange work-around in AS3 for what used to be the onSoundComplete event. I did a bit of Googling before posting this and found an interesting post by Andre Michelle on the topic. That didn't really solve my problem though, as I wanted to demonstrate how to do it in AS3, so I looked at the Flex reference for the AS2 to AS3 conversion of the onSoundComplete event and saw that it was replaced by, according to this, the soundComplete event in flash.media.SoundChannel. I went ahead and tried it out and it seemed to fire off fine on my machine, so here you have it.
Initially I had thought that the following lines of code would do the trick, but they didn't:
-
var s:Sound = new Sound(new URLRequest("music.mp3"));
-
s.addEventListener(Event.COMPLETE, doLoadComplete);
-
s.addEventListener(Event.SOUND_COMPLETE, doSoundComplete);
-
s.play();
Hence why I Googled and tried what I did above, which, as I've already stated, seemed to fix the problem. I'm no expert on sound in Flash but if it works, why question it?
NOTE: I've obviously removed the "music.mp3" file from the download so just grab any .mp3 you have, put it in the same folder that the example files are in, and rename it to music.mp3.
If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.











Thanks for this it really helped me