This demo simulates 4 strings of a guitar, each mapped to one row of keys on your keyboard:
The first key in each row plays the open string while the subsequent keys correspond to the frets. Note that key shapes and positions at the right ends of the rows vary across keyboards. So there the mapping from keys to notes might not fully fit.
A string is "picked" by pressing a key and the corresponding note will play until you release the key, you press another key for the same string, or the string's vibration has faded out after some time. While you cannot play more than one note at a time on a single string, it is possible to play multiple notes on different strings simultaneously (as far as your keyboard properly reports multiple key presses/releases).
For each string the currently playing note is displayed in one of the boxes to the right.
Most browsers do not allow web pages to emit sound before you have interacted with the page (and keyboard input does not count). So click this button to enable audio output:
The purpose of this demo was to experiment with sound generation
in an AudioWorkletNode
.
(See here
for the main JavaScript code and
here
for the worklet processor code. Furthermore
here
is the code for drawing the notes.)
There is one long-lived worklet node per string. Picking and damping works by sending messages.
The code simulates a string sound by superimposing multiple harmonics, each of which is a decaying sine wave. While the actual sound generation by the worklet processor happens in the audio thread, the parameters are calculated in the main JS thread.
As with real guitar strings higher harmonics decay faster than lower ones. So over time a picked string changes from an overtone-rich sound towards a pure sine wave. You can play with the sound generator code to create even more realistic string sounds or sounds of completely different instruments.