package com.aem.utils { import flash.events.Event; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundTransform; /** * Wrapper around the sound class to handle common cases. * * Extends/consolidates the sound interface to provide access to some useful * behavior. You can now stop, pause, and resume the sound without managing * a channel separately. * * @author Alexander Schearer */ public class SoundFx extends Sound { private var _playing:Boolean; private var _looping:Boolean; private var _channel:SoundChannel; /** * @return Boolean Whether the sound is currently playing */ public function get playing():Boolean { return _playing; } public override function play(start:Number = 0, loops:int = 0, transform:SoundTransform = null):SoundChannel { if (_channel) return _channel; _playing = true; _channel = super.play(start, loops, transform); _channel.addEventListener(Event.SOUND_COMPLETE, soundComplete); return _channel; } /** * Loops the sound after it finishes playing indefinitely. */ public function loop(transform:SoundTransform = null):SoundChannel { _looping = true; return play(0, 0, transform); } public function set paused(value:Boolean):void { if (value) pause(); else resume(); } /** * Stops the music keeping track of its current position. Use resume * to play the music from where it was left off. */ private function pause():void { if (!_channel) return; // bug position will not be set unless it's read once var p:uint = _channel.position; _playing = false; _channel.stop(); } /** * Plays the music from wherever it was left off when paused. This * can't be called unless the music has been paused. */ private function resume():SoundChannel { if (!_channel || _playing) return _channel; _playing = true; var p:Number = _channel.position; _channel = null; _channel = play(p); return _channel; } /** * Stops the music disposing of its sound channel. Use play to restart * the track. */ public function stop():void { if (!_channel) return; _playing = false; _looping = false; _channel.stop(); _channel = null; } private function soundComplete(e:Event):void { _playing = false; var transform:SoundTransform = _channel.soundTransform; _channel = null; if (_looping) play(0, 0, transform); } } }