Thursday, November 29, 2007

Controlling Sound in ActionScript 3.0

I was trying to make an audio player for a web site in flash cs 3 or actionscript 3.0 today and it was more than confusing..

i was reading the references and took me a while before i realized that you had to have bunch of other objects to perform tasks like stopping,..

yes.. stopping sound seems easy but not really in actionscript 3.0..but once you get it you won't forget it.

to make an audio or mp3 player in as3 you need three objects.

Sound() - for loading sounds
SoundChannel() - to control playback, stopping
SoundTransform() - to control volume and panning(Left, right stereo stuff)

SoundChannel has .soundTransfor where you can assign SoundTransform() object


var sound:Sound = new Sound();
var sControl:SoundChannel = new SoundChannel();
var vControl:SoundTransform = new SoundTransform();


so now you have 3 objects. let take a look at how they interrelate


sound.load(new URLRequest("yourSong.mp3"); // get the sound clip
sound.addEventListener(Event.COMPLETE, soundLoaded); // triggers a function soundLoaded on load complete
btnStop.addEventListener(MouseEvent.CLICK, stopSound); // create button with inst name of btnStop on stage for it to work
btnVolumeUp.addEventListener(MouseEvent.CLICK, changeVolume);

function soundLoaded(e:Event):void
{
sControl = sound.play(); // this is the hard part...
}

function stopSound(e:MouseEvent):void
{
sControl.stop(); // sound.stop() won't work for some reason.. or for a good reason..
}

function changeVolume(e:MouseEvent):void
{
vControl.volume += .1; // since volume property's range is 0 to 1
sControl.soundTransform = vControl; // assign that info to control
}


well this should blow up your speaker since it only goes up. try it at your own risk and i didn't tell you to do it. so you can't sue me. you should spend your time in other things like try implementing decreasing volume or much more flexible way of controling volume, etc.

No comments: