package 
{    
    import com.adobe.viewsource.ViewSource;
    
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.BitmapDataChannel;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
  
    [SWF(backgroundColor=0x2b2b2b)]               
    public class BitmapDataNoiseTest extends Sprite
    {
        private var _sprite:Sprite;
        private var _bitmap:Bitmap;
        private var _sound:Sound;
        private var _channel:SoundChannel;      
        private var _isPlaying:Boolean = false;      
        
        public function BitmapDataNoiseTest()
        {
            ViewSource.addMenuItem(this, "srcview/index.html");            
            stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;
            stage.align = flash.display.StageAlign.TOP_LEFT;
            
            // Create noise sprite and bitmap
            _sprite = new Sprite();
            var bitmapData:BitmapData = new BitmapData(180, 180);
            var seed:int = int(Math.random() * 100);
            bitmapData.noise(seed, 0, 0xFF, BitmapDataChannel.RED, true);
            _bitmap = new Bitmap(bitmapData);
            this.addChild(_sprite);
            _sprite.addChild(_bitmap);
            
            // Load sound
            _sound = new Sound(new URLRequest("sounds/noSignal.mp3"));
            
            // Add mouse listeners
            _sprite.addEventListener(MouseEvent.MOUSE_OVER, play);
            _sprite.addEventListener(MouseEvent.MOUSE_OUT, stop);
            
            // Add animation handler
            this.addEventListener(Event.ENTER_FRAME, updateNoise);
        }
        
        /**
         * Noise animation handler.
         */
        public function updateNoise(event:Event):void 
        {
            // Reseed bitmap data
            var seed:int = int(Math.random() * 100);
            _bitmap.bitmapData.noise(seed, 0, 0xFF, BitmapDataChannel.RED, true);
        }        
    
        /**
        * Plays noise sound
        */
        public function play(event:MouseEvent):void
        {
            if (!_isPlaying)
            {
                _channel = _sound.play(0, int.MAX_VALUE);
                _isPlaying = true;
            }        
        }
    
        /**
        * Stops playing noise sound
        */
        public function stop(event:MouseEvent):void
        {
            if(_isPlaying && _channel != null) 
            {
                _channel.stop();
                _isPlaying = false;
            }
        }
    }
}