package musica{
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
    import flash.utils.Timer;

    public class trilha extends Sprite {
        public var url:String = "musica/billi2.mp3";
        public var soundFactory:Sound;
        public var channel:SoundChannel;
        public var positionTimer:Timer;
		public var leuSom:Boolean;
		public var position:Number;
		public var tocando:Boolean;

        public function trilha() {
            leuSom = false;
			var request:URLRequest = new URLRequest(url);
            soundFactory = new Sound();
            soundFactory.addEventListener(Event.COMPLETE, completeHandler);
            soundFactory.addEventListener(Event.ID3, id3Handler);
            soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            soundFactory.load(request);
			channel = soundFactory.play();
			channel.stop();
			position = 0;

            positionTimer = new Timer(50);
            positionTimer.addEventListener(TimerEvent.TIMER, positionTimerHandler);
            positionTimer.start();
        }
		
public function stopMusic():void
{
    if (soundFactory != null)
    {
	position = channel.position;
	channel.stop();
	channel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
	tocando = false;
    }
}
public function playMusic():void
{
    if(channel.hasEventListener(Event.SOUND_COMPLETE)){ 
	channel = soundFactory.play(0);
	}
	else{
	channel = soundFactory.play(position);
	}
	tocando = true;
	channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
}

        

        public function positionTimerHandler(event:TimerEvent):void {
            //trace("positionTimerHandler: " + channel.position.toFixed(2));
        }

        public function completeHandler(event:Event):void {
			leuSom = true;
         // channel = soundFactory.play(0, int.MAX_VALUE);
		  // trace("completeHandler: " + event);
        }

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

        public function ioErrorHandler(event:Event):void {
            //trace("ioErrorHandler: " + event);
            //positionTimer.stop();       
        }

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

        public function soundCompleteHandler(event:Event):void {
			 if (soundFactory != null)
    {
        soundFactory.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
		playMusic();
    }
        }
    }
}