Sunday, April 6, 2008

Creating a toggling mute button in AS3

Here is some code to create a toggle mute button for sounds in AS3

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;

private var muted:Boolean = false;
private var soundFactory:Sound;
private var soundClip:SoundChannel;
private var soundVolume:SoundTransform;
private var url:String = "myclip.mp3";
private var request:URLRequest = new URLRequest(url);


// create a new SoundTransform obj
soundVolume = new SoundTransform();
soundVolume.volume = 1;

// now create a new sound obj
soundFactory = new Sound();
// now load the mp3
soundFactory.load(request);
// and play it
soundClip = soundFactory.play();

// now set the volume of the clip --
//you need to do this AFTER the clip is playing
soundClip.soundTransform = soundVolume;

// here is an eventHandler that will mute and unmute the volume
private function toggleVolumeListener(evt:Event):void{
//toggle the boolean
_muted = !_muted;
if(_muted){
// first set the var for use with other sound clips
soundVolume.volume = 0;
// now reset the soundTransform obj of the soundClip
soundClip.soundTransform = soundVolume;
}else{
soundVolume.volume = 1;
// now reset the soundTransform obj of the soundClip
soundClip.soundTransform = soundVolume;
}
}

No comments: