Home > Actionscript 3, Flash > Tutorial actionscript3 – Loading sound and play as loop

Tutorial actionscript3 – Loading sound and play as loop

DOWNLOAD EXAMPLE

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
 
	/**
	 * This class load a sound and play it in loop.
	 * @author http://www.miguelmoraleda.com
	 */
	public class Main extends Sprite
	{
		private var soundFactory:Sound;
		private var song:SoundChannel;
 
		public function Main()
		{
			super();
 
			loadSound("sound.mp3");
		}
 
		/**
		 * Load the sound
		 * @param	url
		 */
		private function loadSound(url:String):void
		{
			var request:URLRequest = new URLRequest(url);
            soundFactory = new Sound();
            soundFactory.addEventListener(Event.COMPLETE, completeHandler);
            soundFactory.load(request);
		}
 
		/**
		 * When sound is loaded, play it.
		 * @param	e
		 */
		private function completeHandler(e:Event):void
		{
			soundFactory.removeEventListener(Event.COMPLETE, completeHandler);
			playSound();
		}
 
		/**
		 * Play the sound and add listener to sound complete.
		 */
		private function playSound():void
		{
            song = soundFactory.play();
			song.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
		}
 
		/**
		 * when the sound is finish play again.
		 * @param	e
		 */
		private function soundCompleteHandler(e:Event):void
		{
			song.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
			playSound();
		}
	}
}



Categories: Actionscript 3, Flash Tags:
  1. July 23rd, 2009 at 12:50 | #1

    The problem with this method is that it creates a small interval between each play through of the loop. If you use normal looping you don’t have this problem. I’m facing this “interval” problem myself.

  2. Forrest
    October 21st, 2009 at 17:13 | #2

    same problem as Indigon’s, I figured out one way, hoping there’s a better way to do the trick, my method is to attachSound from the library instead of loading it from a url.

*

Spam Protection by WP-SpamFree

Get Adobe Flash playerPlugin by wpburn.com wordpress themes