In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Voice Transducer

Get Adobe Flash player
by kotobuki 12 Sep 2009
/**
 * Copyright kotobuki ( http://wonderfl.net/user/kotobuki )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/ZiGI
 */

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.media.Microphone;
    import flash.media.Sound;
    import flash.media.SoundTransform;
    import flash.net.URLRequest;
    import flash.text.TextField;
    import flash.utils.getTimer;

    public class VoiceTransducer extends Sprite {
        private var _mic:Microphone;

        private var _tf:TextField;

        private const URL_OF_SOUND_FILE:String = "http://localhost/sounds/pig0";

        private const NUM_OF_SOUND_FILES:int = 6;

        private var _wasActive:Boolean = false;

        private var _sound:Array;

        private var _lastPlayed:int = 0;

        public function VoiceTransducer() {
            _sound = new Array(NUM_OF_SOUND_FILES);
            for (var i:int = 0; i < NUM_OF_SOUND_FILES; i++) {
                _sound[i] = new Sound();
                _sound[i].addEventListener(Event.COMPLETE, onLoadComplete);
                _sound[i].load(new URLRequest(URL_OF_SOUND_FILE + (i + 1) + ".mp3"));
            }

            _mic = Microphone.getMicrophone();
            _mic.setLoopBack();
            _mic.setUseEchoSuppression(true);

            _tf = new TextField();
            this.addChild(_tf);

            var transform:SoundTransform = new SoundTransform();
            transform.volume = 0.0
            _mic.soundTransform = transform;
        }

        private function onLoadComplete(e:Event):void {
            this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        private function onEnterFrame(e:Event):void {
            _tf.text = "level: " + _mic.activityLevel;
            var isActive:Boolean = (_mic.activityLevel > 20) ? true : false;
            var now:int = getTimer();

            if (!_wasActive && isActive) {
                if (now - _lastPlayed > 200) {
                    _sound[Math.floor(Math.random() * NUM_OF_SOUND_FILES)].play();
                    _lastPlayed = now;
                } else {
                    isActive = false;
                } 
            }
            _wasActive = isActive;
        }
    }
}