Sunday, May 22, 2011

Loop sound


1:  //Stop at this frame
   2:  stop(); 
   3:   
   4:  //Create a new sound object
   5:  var music:Sound = new Sound()
   6:   
   7:  //Set location of sound file – if it is external – using a URLRequest object
   8:  var req:URLRequest = new URLRequest("audio/bongos.mp3");
   9:   
  10:  //Create a new SoundChannel object
  11:  var channel:SoundChannel; 
  12:   
  13:  //load music file – via url request object – into channel object
  14:  music.load(req);
  15:  playMusic(); 
  16:   
  17:  //Boolean checks if the sound is playing
  18:  var musicIsOn:Boolean = true;
  19:   
  20:  //An event listener for a button that stops the music (YOU DONT HAVE TO PUT THIS IN)
  21:  btnMusic.addEventListener(MouseEvent.CLICK, stopMusic); 
  22:   
  23:  function stopMusic(evt:Event):void {
  24:      if(musicIsOn)
  25:      {
  26:          trace("stop");
  27:          channel.stop();
  28:          musicIsOn = false;
  29:      } else {
  30:          playMusic();
  31:          musicIsOn = true;
  32:      }
  33:  } 
  34:   
  35:  function playMusic():void{
  36:      trace("play");
  37:   
  38:  //play music through the SoundChannel
  39:      channel = music.play();
  40:   
  41:  //add an event listener that reacts when the sound being played 
  42:  //is completed and repeats the sound
  43:      channel.addEventListener(Event.SOUND_COMPLETE, repeat);
  44:  } 
  45:   
  46:  function repeat(evt:Event):void {
  47:      if(channel != null)
  48:      {
  49:   
  50:  //without removing the event listener the sound clip will play only twice
  51:  //I am not sure why but it feels like the event listener gets disposed of
  52:  //once used by default.
  53:          channel.removeEventListener(Event.SOUND_COMPLETE, repeat);
  54:          playMusic();
  55:      }
  56:  }

No comments:

Post a Comment