Dynamic Sound Generator in AS3 ( basic piano )

The source code and a brief explanation can be found here
package
{
import flash.display.Sprite;
import flash.media.SoundChannel;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.events.KeyboardEvent;
import flash.events.SampleDataEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent; </span>

public class SoundGeneration extends Sprite
{
private var _sound            :Sound                = null;
private var _channel          :SoundChannel     = null;
private var _pitchRatios      :Object              = null;
private const BASE_PTICH  :Number              = 440;
 private var _pitch             :Number             = 1;
 private var _timer             :Timer                = null;

public function SoundGeneration()
 {
 _pitchRatios = {97:1, 115:1.059, 100:1.122, 102:1.189, 103:1.259, 104:1.334, 106:1.414, 107:1.498, 108:1.587};
 _timer = new Timer(100);
 _timer.addEventListener(TimerEvent.TIMER, TimerStop,false, 0, true);
 stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDown, false, 0, true);
 stage.focus = this;
 }

 private function KeyDown($e:KeyboardEvent):void
 {
 if(_timer.running == false) _timer.start();
 PlaySound(_pitchRatios[$e.charCode])
 }

 private function PlaySound($pitchRatio:Number):void
 {
 StopSound();
 _pitch = BASE_PTICH * $pitchRatio;
 _sound = new Sound();
 _sound.addEventListener(SampleDataEvent.SAMPLE_DATA, WaveGenerator, false, 0, true);
 _channel = _sound.play();
 }

 private function WaveGenerator($e:SampleDataEvent):void
 {
 var $lev:Number;
 for (var i:uint = 0; i < 8192; i++)
{
$lev = 0;
$lev += Math.sin((i + $e.position) * Math.PI / (44100 / _pitch ));
$lev /= 2;
$e.data.writeFloat($lev);
$e.data.writeFloat($lev);
}
 }

 private function TimerStop($e:TimerEvent):void
 {
 if(_timer.running) _timer.stop();
 StopSound();
 }

 private function StopSound():void
 {
 if (_channel)
 {
 _channel.stop();
 _sound.removeEventListener(SampleDataEvent.SAMPLE_DATA,SineWaveGenerator);
 }
 }
 }
}
Advertisements

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