Friday, July 30, 2010

Sound class in Actionscript 3: Part 5

In today's lesson we will learn about sound amplitude, volume and stereo-balance.

Actionscript 3 gives access to left and right stereo sound channels - SoundChannel object's properties leftPeak and rightPeak. Their values can be in range from 0.0 to 1.0, where 1.0 is the maximal value.

Let's create a simple example of two bars that represent two stereo sound channels:

stage.addEventListener(Event.ENTER_FRAME, loop);
var mysound = new Sound(new URLRequest("song.mp3"));
var theChannel:SoundChannel
theChannel = mysound.play();

function loop (event:Event){

graphics.clear(); 
graphics.beginFill(0x0066CC); 
graphics.drawRect(10, 10, theChannel.leftPeak * 150 , 10); 
graphics.endFill(); 
graphics.beginFill(0x0066CC); 
graphics.drawRect(10, 25, theChannel.rightPeak * 150, 10); 
graphics.endFill(); 
}

Note that this isn't the volume! Volume is a property of property soundTransform of object SoundChannel. It's just like with the fonts - you first create the format, then you apply it to the text. Same here! Values of the volume property range from 0.0 to 1.0.

var mysound = new Sound(new URLRequest("song.mp3"));
var theChannel:SoundChannel = mysound.play();
var mytransform:SoundTransform = new SoundTransform();
mytransform.volume = .7
theChannel.soundTransform = mytransform

Stereo-balance (left and right speakers) is done the same way:

var mysound = new Sound(new URLRequest("song.mp3"));
var theChannel:SoundChannel = mysound.play();
var mytransform:SoundTransform = new SoundTransform();
mytransform.pan = -1.0
theChannel.soundTransform = mytransform

With the code above, the sound will only be heard through the left speaker (values range from -1.0 to 1.0). You can also set volume and stereo-balance values when you create the SoundTransform (first parameter volume, second parameter - stereo-balance):

var mysound = new Sound(new URLRequest("song.mp3"));
var theChannel:SoundChannel = mysound.play();
var mytransform:SoundTransform = new SoundTransform(.7, -1.0);
theChannel.soundTransform = mytransform

Thanks for reading!

Related:

Sound class in Actionscript 3: Part 1
Sound class in Actionscript 3: Part 2
Sound class in Actionscript 3: Part 3
Sound class in Actionscript 3: Part 4
Sound class in Actionscript 3: Part 6

No comments:

Post a Comment