Saturday, July 21, 2012

AS3: Fading Sound

Music playing, something that is very important to an interactive website, therefore I'm going to show you how to create a pretty simple fade in and fade out effect for your background music today.

Main class file - Main.as
package com.zcs.main 
{ 
 import flash.display.MovieClip;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import com.greensock.TweenLite;
 import flash.media.SoundChannel;
 import flash.media.SoundTransform;
 
 public class Main extends MovieClip 
 {
  private var _btn_mc:MovieClip;
  
  private var bgSound:Sound1;
  
  //Variable to toggle the playing state
  private var isPlaying:Boolean = false;
  
  private var soundChannel:SoundChannel;
  private var soundT:SoundTransform;
  
  public function Main() 
  {
   this.addEventListener(Event.ADDED_TO_STAGE, stageEvent);
  }
  
  private function stageEvent(event:Event):void
  {
   //Setup up the listener for the play stop button.
   _btn_mc = this.getChildByName("btn_mc") as MovieClip;
   _btn_mc.buttonMode = true;
   _btn_mc.addEventListener(MouseEvent.CLICK, clickEvent);
   
   //Create an instance for the Sound Object
   bgSound = new Sound1();
   
   //Create a Sound Transform instance that will be used
   //to modify the volume of the Sound Object 'bgSound'.
   soundT = new SoundTransform();
   soundT.volume = 0;
   
   //In Flash, we need to assign the audio that we want
   //to play to a Sound Channel
   soundChannel = new SoundChannel();
   soundChannel = bgSound.play(0,9999);
   soundChannel.soundTransform = soundT;
   
   //Call the function toggleSound()
   toggleSound();
  }
  
  /*
   If the Sound Object isn't 'playing', we need to slowly
   increase the volume of the sound channel to the max.
   If it's 'playing', slowly decrease the volume to 0.
  */
  private function toggleSound():void
  {
   if(isPlaying)
   {
    _btn_mc.gotoAndStop("stopping");
    TweenLite.to(soundT, 1, {volume:0, onUpdate:updateSoundEvent, 
        onComplete:updateSoundEvent});
   }else{
    _btn_mc.gotoAndStop("playing");
    TweenLite.to(soundT, 1, {volume:1, onUpdate:updateSoundEvent, 
        onComplete:updateSoundEvent});
   }
   isPlaying = !isPlaying;
  }
  
  //When the volume changes, we need to update the sound transform
  //of the sound channel.
  private function updateSoundEvent():void
  {
   soundChannel.soundTransform = soundT;
  }
  
  //Upon clicking the button, run the function toggleSound().
  private function clickEvent(event:Event):void
  {
   toggleSound();
  }
 }
}
* Click here for the demo.
^ Click here for the source files of the demo.

No comments:

Post a Comment