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

Dynamic Sound Generationで蛙の歌

Get Adobe Flash player
by 024t910 14 Jan 2009
// write as3 code here..
package  {
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.media.Sound;
	import flash.events.SampleDataEvent;
	import flash.media.*;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
        import flash.display.Sprite;

	public class FrogSong extends Sprite{
                //初期パラメータを設定
		private var freq:Number = 220;
		private var rate:Number = 44100;
		private var baseRate:Number = 44100;
		private var noise:Number = 0;

                 
                //音声の再生を700ms秒に設定
		private var timer:Timer = new Timer (700,0);
		
                //簡易楽譜
		private var rateArray:Array = new Array ();
		
                //再生用Sound系クラス
		private var sound:Sound = new Sound();
		private var soundChannelObject:SoundChannel = new SoundChannel ();
		
		public function FrogSong() {
                        //各コードの比率を設定
		        var C:Number = 1;
		        var D:Number = 9 / 8;
		        var E:Number = 5 / 4;
        		var F:Number = 4 / 3;
	        	var G:Number = 3 / 2;
		        var A:Number = 5 / 3;
		        var B:Number = 15 / 8;
                       //蛙の歌を配列にして楽譜化
			rateArray = [C, D, E, F, E, D, C, C, E, F, G, A, G, F, E, E, C, 0, C, 0, C, 0, C, 0, C, D, E, F, E, D, C];
			rate = baseRate/rateArray.shift();
			timer.addEventListener (TimerEvent.TIMER, onTimer);
			timer.start ();
			sound.addEventListener (SampleDataEvent.SAMPLE_DATA, onSamplesCallback);
			soundChannelObject = sound.play();
		}

		private function onTimer (e:TimerEvent):void {
			if (!rateArray.length) {
				timer.stop ();
				soundChannelObject.stop ();
				dispatchEvent (new Event(Event.COMPLETE));
			}else{
        			rate = baseRate/rateArray.shift();
                        }
		}
		
		private function onSamplesCallback (e:SampleDataEvent) :void{
			for(var i:int=0; i<2048; i++){
				noise += (freq) / rate;
                                //左音声の波形データの生成
				var samples:Number = noise * Math.PI*2;
				e.data.writeFloat(Math.sin(samples));
                                //右音声の波形データの生成
				var samples2:Number = noise * Math.PI;
				e.data.writeFloat(Math.sin(samples));
			}
		}
		
		
	}
	
}