Thursday, January 21, 2010

Play sound as a LOOP in AS3

//In AS3 an event Event.SOUND_COMPLETE that fires when the sound finishes, so when that fires you should start the sound again, and your sound will be play as a loop.


var sndReq:URLRequest=new URLRequest("Assets/Audio/drums01.mp3");
var snd:Sound = new Sound();
var channel:SoundChannel = new SoundChannel();
snd.load(sndReq);
soundOn.addEventListener(MouseEvent.CLICK, playSound);
soundOff.addEventListener(MouseEvent.CLICK, stopSound);
function playSound(event:MouseEvent):void {
channel=snd.play();
channel.addEventListener(Event.SOUND_COMPLETE,loopSound);
}
function loopSound(event:Event) {
playSound();
}
function stopSound(event:MouseEvent):void {
channel.stop();
}

Monday, January 18, 2010

Loading External Sound

Sound, whether in the form of music or sound effects, is an important part of any flash game. While you may be able to get away with controlling sound with the time-line in an animation, a game must be a bit more dynamic and you will almost always need to control the sound with action-script. This tutorial will help you understand not only control sound in action-script 2, but avoid potential problems.
Loading external sound into your Flash projects using AS2 is a fairly easy task. Using AS3 to load external sounds is just as simple. I am going to quickly go over how to load an external sound file using AS3 in comparison to AS2 syntax.

Loading external sound using AS2

var snd:Sound = new Sound ();
snd.loadSound("song.mp3", true);
snd.onSoundComplete = function() {
snd.start();
};


Loading external sound using AS3



var snd:Sound = new Sound();
var channel:SoundChannel = new SoundChannel();
snd.load(new URLRequest("song.mp3"));
snd.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
function onComplete(evt:Event):void {
channel = snd.play();
}

In AS3 the SoundChannel class is used to create a separate channel for each new sound played. By placing each sound in its own channel, you can work with multiple sounds but control each sound separately.