Astro Dynamic Sound!

May 15 2008 Published by under Flash

Andre Michelle and others have been telling Adobe to Make Some Noise, and Adobe has listened!

A preview release of Flash Player 10 “Astro” was released today, and in it is the capability to dynamically create sounds. See this demo (of course you’ll need the new player installed):

Here I’m creating two wave forms, one controlled by the mouse’s X position, and one by the Y, and combining them into a single dynamic sound, also visualized.

The way the new sound creation works is you listen for a “SAMPLES_CALLBACK” event on the sound object. This is fired when the playing sound object is almost out of sound to play. In the event handler for this event, you fill up the sound’s sampleCallbackData property with a bunch of new sample. This property is a byte array, so you write a bunch of floating point numbers to it. One for the left channel, then one for the right channel.

Here is about the simplest example:

[as]var sound:Sound = new Sound();
sound.addEventListener(Event.SAMPLES_CALLBACK, onSamplesCallback);;

var freq:Number = 440;
var rate:Number = 44100;
var phase:Number = 0;

function onSamplesCallback(event:Event):void
for(var i:int = 0; i < 512; i++)
phase += freq / rate;
var phaseAngle:Number = phase * Math.PI * 2;
var sample:Number = Math.sin(phaseAngle);

Note that these are beta APIs and are likely to change. If you are viewing this post any time after spring / early summer 2008, the above code will probably not compile, and I can't even guarantee that the SWF will work in future versions of the player. But this is a glimpse of what is to come.

freq is the frequency of the sound you want to create. rate is 44100 samples per second, which is what the new model uses. Use phase to hold a number, multiplied times 2PI to give you the angle, take the sine of that angle to get a sine wave. We write that to samplesCallbackData twice - once for left, once for right. You could write different values here to go stereo. Here, we write 512 samples at a time. When those are almost used up, we'll get another callback and write another 512, so the sound will continue to play.

Thanks to Tinic Uro for pushing this one through! A lot more (and more accurate and better coded) information here:

30 responses so far. Comments will be closed after post is one year old.