package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
	import flash.media.SoundTransform;
    import flash.net.URLRequest;
	import flash.external.ExternalInterface;
	import flash.display.LoaderInfo;

    public class SoundExample extends Sprite {
        private var url:String = "MySound.mp3";
        private var song:SoundChannel;
		private var soundFactory:Sound = new Sound();
		private var trans:SoundTransform = new SoundTransform();
		private var muted:Boolean = false;

        public function SoundExample() {
			if (getFlashVars().url)
			{
				url = getFlashVars().url;
			}
			
            var request:URLRequest = new URLRequest(url);
            
            soundFactory.addEventListener(Event.COMPLETE, completeHandler);
            soundFactory.addEventListener(Event.ID3, id3Handler);
            soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            soundFactory.load(request);
			
			if (ExternalInterface.available)
			{
				ExternalInterface.addCallback("toggleAudio", toggleAudio);
			}
			
			//song.addEventListener(Event.SOUND_COMPLETE, sc);
        }
		
		private function getFlashVars():Object {
			return Object( LoaderInfo( this.loaderInfo ).parameters );
		}
		
		public function toggleAudio(v:String):void
		{
			muted = !muted;
			
			if (muted)
			{
				trans.volume = 0;
			}else {
				trans.volume = 1;
			}
			
			song.soundTransform = trans;
		}
		
        private function completeHandler(event:Event):void {

            song = soundFactory.play(0, 99999);
			
            trace("completeHandler: " + event);
        }

        private function id3Handler(event:Event):void {
            trace("id3Handler: " + event);
        }

        private function ioErrorHandler(event:Event):void {
            trace("ioErrorHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void {
			//trace("progressHandler: " + event);
        }
    }
}