RSS LinkedIn Twitter

Changing the Volume on Embedded Audio (Flex)

February 23rd, 2011 Categories: Uncategorized

In Flex you can embed an audio file into your swf (as opposed to streaming it or loading it remotely via a URLRequest). You do that in the same way you embed other assets using the [Embed] metadata tag.

[Embed(source="MySound.mp3")]
public var soundClass:Class;

To play the sound, you simply instantiate an instance of it, and call play. Optionally you can pass in a SoundTransform object that sets the volume, fade, etc. As follows:

var snd:Sound = new soundClass() as Sound;
var trans:SoundTransform = new SoundTransform(.01);
snd.play(0,0,trans);

The method signature of play is:

play(startTime:Number = 0,
     loops:int = 0,
     sndTransform:flash.media:SoundTransform = null):SoundChannel

And there is no way to set the transform on the sound directly, other than the play method. And it didn’t seem trivial to track the location you are at in the audio so if you called play() again, you could start it from the exact point where you left off. So the question is, what if you want to change the volume? The solution is to assign the playing sound to a channel, which does allow you to specify a SoundTransform without having to call play again.

Here is my complete solution, with only a “volume up” button.

[Embed(source="MySound.mp3")]
public var soundClass:Class;
public var snd : Sound;
public var vol : Number = 0.01;
public var chan : SoundChannel = new SoundChannel();
protected function onCreationComplete(event:FlexEvent):void {
    snd = new soundClass() as Sound;
    var trans : SoundTransform = new SoundTransform(vol);
    chan = smallSound.play(0,0,trans);
}
protected function volUp_clickHandler(event:MouseEvent):void {
    vol += .1;
    var trans : SoundTransform = new SoundTransform(vol);
    chan.soundTransform = trans;
}

This was just a quick hack.. some more investigation might reveal that you can just modify the volume property of the channel’s soundTransform property rather than reinstantiating a new one each time.

Tags:
No comments yet.

Leave a Comment

*