Creating sound waves with JavaScript

Sound waves can be generated using math equations. For example, the frequency of 440 Hz produces the musical note known as "A4". This can be created by a sine wave that vibrates the audio output 440 times in one second. Here we use JavaScript to synthesize sounds creating waves and frequencies with math equations. The resulting waves can be visualized in the graphs below using the <canvas> HTML5 element.

All overlapped points over time (44100 pixels in 1 second):
Samples in the middle of the sound playing (650 pixels):

Click to hear interesting sounds and waves:

Change code below (try frequency from 110 to 12000) and click:

The equations above use principles of Frequency Modulation Synthesis (FM Synthesis).

Clarinet sound: generated by a sum of odd harmonics (1, 3, 5, 7, 9, 11, 13):

Violin sound: generated by a sum of harmonics with decreasing amplitudes:
sin(w)+1/2 * sin(w*2) + 1/3*sin(w*3) + 1/4*sin(w*4) + 1/5*sin(w*5) + 1/6*sin(w*6)
The "vibrato" effect is created by multiplying the equation by a low frequency (6 Hz).
The "attack time" effect (start time where the sound increases its amplitude) is created by multiplying the equation by (1-exp(-t*3)).

White noise: generated by creating random samples.

If you find other equations that emulate interesting sounds, effects or musical instruments, please post in the comments.

Each note has its own frequency, for example the middle C (C4) in the piano is 523.26 Hertz:

C4 = 261.63 Hz C5 = 523.26 Hz
C#4 = 277.18 Hz C#5 = 554.37 Hz
D4 = 293.66 Hz D5 = 587.33 Hz
D#4 = 311.13 Hz D#5 = 622.25 Hz
E4 = 329.63 Hz E5 = 659.26 Hz
F4 = 349.23 Hz F5 = 698.46 Hz
F#4 = 369.99 Hz F#5 = 739.99 Hz
G4 = 392 Hz G5 = 783.99 Hz
G#4 = 415.3 Hz G#5 = 830.61 Hz
A4 = 440 Hz A5 = 880 Hz
A#4 = 466.16 Hz A#5 = 932.33 Hz
B4 = 493.88 Hz B5 = 987.77 Hz
See also MIDI note numbers, note frequencies and keyboard note position I will create an interactive piano keyboard in my next post.