One of the new features of Flash Player 10 is dynamic sound generation or sound synthesis, which is the ability to write directly to the Sound object and create audio from scratch.
This is a very easy process – in a nutshell, you need to create an event handler for the Sound object’s SampleDataEvent.SAMPLE_DATA event which returns the wave form. This could be a basic sine wave based on a combination of the event’s position property and a loop of up to 8192 samples.
Why 8192 samples? Well, the Flash Player samples audio at the same rate as an audio CD – 44.1k samples per second, and we need to supply a sample to each channel (left and right) which gives us 8192.
So a basic sine wave function could look something like this:
Math.sin((Number(position)/Math.PI/4 * frequency))* volume
Where the position is the sum of the SampleDataEvent.position and our loop counter.
We can also use the sin function to approximate a square wave using a Fourier series:
var square:Number=Math.sin((Number(position)/Math.PI/2 * frequency)) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 3)) / 3) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 5)) / 5) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 7)) / 7) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 9)) / 9) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 11)) / 11) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 13)) / 13) +
(Math.sin((Number(position)/Math.PI/4 * frequency * 15)) / 15)
Fourier taught us that any possible waveform can be synthesized from a sum of sine waves, so my rough and ready demo offers four separate sound channels that have independent frequency and amplitude sliders that sum together to create the sound.
It’s not exactly MVC, but in my demo each ChannelEditor class is responsible for calculating its own value for any given position. The main class, FlexMonkeySynth, sums each of the four values and supplies that to the event handler.
Have a play – the top slider for each channel controls the frequency and the lower controls the amplitude. The radio buttons allow you to select between a square and a sine wave. Of course, the source code is enabled.
The skin comes from Bhavin Padhiyar and is available on http://scalenine.com/themes/machine/Machine.html#.
View comments