Tutorial: How to create an Audio fader with audio fade in and fade out?
Technology: Adobe Flash or Flash Builder or Adobe Flex with ActionScript 3.0
Description: In this tutorial we are going to create audio fade in and fade out effects on click of two buttons.
Project Source File: AudioFadeInOut.zip
Content: To create audio fader that fades the audio in and out we just need a timer which can transform the sound up and down with in the prescribed time. The functionality of the below code is as follows:
When clicked, it starts a timer which increases the sound from 0-1(lowest to highest volume) in 1.5 seconds. You can change the time by changing the value of 50 in "Timer(50,30)". Similarly the fade out function can be implemented to decrease the volume from maximum to minimum in 1.5 seconds, thus creating the fade in and fade out effect in sound for flash.
import flash.media.Sound;
import fl.transitions.Tween;
btnFadeIn.addEventListener(MouseEvent.CLICK,fadeInClick);
btnFadeOut.addEventListener(MouseEvent.CLICK,fadeOutClick);
btnPlay.addEventListener(MouseEvent.CLICK,btnPlayClick);
btnStop.addEventListener(MouseEvent.CLICK,btnStopClick);
//Play sound with class name "sound1" from library
var snd:sound1 = new sound1();
var channel:SoundChannel;
var sAmbienceVol:SoundTransform;
//play music
function btnPlayClick(evt:Event):void {
channel=snd.play(0,20);
}
//stop music
function btnStopClick(evt:Event):void {
channel.stop();
}
//fade In on mouse over code
function fadeInClick( evt:Event):void {
//fadein time 50 msec x 30 = 1500 msec
var soundFadeInTimer:Timer=new Timer(50,30);
soundFadeInTimer.addEventListener("timer",soundFadeIn);
soundFadeInTimer.start();
fadeInIncr=0.1;
}
//Fade In (sound from low to high)
var fadeInIncr:Number=0.1;
function soundFadeIn(e:TimerEvent) {
fadeInIncr+=1/30;
sAmbienceVol=new SoundTransform(fadeInIncr,0);
channel.soundTransform=sAmbienceVol;
trace(fadeInIncr);
}
function fadeOutClick( evt:Event):void {
//fadeout time 50 msec x 30 = 1500 msec
var soundFadeOutTimer:Timer=new Timer(50,30);
soundFadeOutTimer.addEventListener("timer", soundFadeOut);
soundFadeOutTimer.start();
fadeOutIncr=1;
}
//Fade Out (sound from high to low)
var fadeOutIncr:Number=1;
function soundFadeOut(e:TimerEvent) {
fadeOutIncr-=1/30;
sAmbienceVol=new SoundTransform(fadeOutIncr,0);
channel.soundTransform=sAmbienceVol;
trace(fadeOutIncr);
}