jump to navigation

Loading sound and play as loop :Actionscript 3 September 19, 2010

Posted by Tournas Dimitrios in Actionscript.
trackback

Load sound at runtime and loop it with this class . A bit of work has to be done on this class so that play , stop , resume and pause can be implemented .. A future post will carry out the pre-mentioned functionality .

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.tournasdimitrios1.wordpress.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();
		}
	}
}
Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s