Web Audio API Instruments — Piano, Guitar and Kalimba, Three Ways to Make Sound
How three Web Audio API demos make sound: a triangle oscillator per piano key, Karplus-Strong synthesis for the guitar, and two layered oscillators for the kalimba.
Three instruments, three ways to make sound
The site's piano, guitar and kalimba demos play no audio files in the browser. They are implemented by synthesising sound with the Web Audio API, and each instrument does it differently.
The piano plays one triangle oscillator per key with a short fade in and fade out. The guitar uses no oscillator: it writes each pluck into an AudioBuffer with Karplus-Strong synthesis and plays the buffer. The kalimba layers a triangle at the note frequency with a sine at twice the frequency.
Creating and resuming the AudioContext
The three demos do not share an AudioContext. Each one creates its own the first time it plays a sound.
If the AudioContext state is suspended, the demo calls resume() before playing. If creating the AudioContext throws, the demo plays nothing.
Piano: frequencies from C4
The piano covers two octaves, C4 to B5: 14 white keys and 10 black keys, 24 keys in total.
Each key's frequency comes from 12-tone equal temperament with C4 = 261.63 Hz as the reference. With semitone counted from C4, the frequency is 261.63 times 2 to the power of semitone / 12. The reference is C4, not A4 = 440 Hz.
const BASE_FREQ = 261.63
function noteToFreq(note: string): number {
const names = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
const name = note.slice(0, -1)
const octave = Number(note.slice(-1))
const semitone = names.indexOf(name) + (octave - 4) * 12
return BASE_FREQ * 2 ** (semitone / 12)
}Piano: pressing a key
Pressing a key that is not already sounding creates one OscillatorNode for that key, sets its type to triangle, and connects it through a GainNode to the output.
The gain starts at 0 and rises linearly to 0.25 over 0.02 seconds. It stays at 0.25 while the key is held. There is no separate decay stage or sustain level.
const noteOn = useCallback(
(note: string) => {
if (activeRef.current.has(note)) return
const ctx = getCtx()
if (!ctx) return
const osc = ctx.createOscillator()
const gain = ctx.createGain()
osc.type = 'triangle'
osc.frequency.value = noteToFreq(note)
gain.gain.setValueAtTime(0, ctx.currentTime)
gain.gain.linearRampToValueAtTime(0.25, ctx.currentTime + 0.02)
osc.connect(gain)
gain.connect(ctx.destination)
osc.start()
activeRef.current.set(note, { osc, gain })
setPressed((prev) => new Set(prev).add(note))
},
[getCtx],
)Piano: releasing a key, and the Sustain toggle
Releasing a key ramps the gain exponentially down to 0.001 over 0.3 seconds, and the oscillator stops at the same moment.
The piano has a Sustain toggle. While Sustain is ON, releasing a key does not stop the note. Turning Sustain OFF stops every sounding note with the same 0.3 second fade.
const noteOff = useCallback((note: string) => {
if (sustainRef.current) return
const entry = activeRef.current.get(note)
if (!entry) return
const ctx = audioCtxRef.current
if (!ctx) return
entry.gain.gain.cancelScheduledValues(ctx.currentTime)
entry.gain.gain.setValueAtTime(entry.gain.gain.value, ctx.currentTime)
entry.gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.3)
entry.osc.stop(ctx.currentTime + 0.3)
activeRef.current.delete(note)
setPressed((prev) => {
const s = new Set(prev)
s.delete(note)
return s
})
}, [])Piano: keyboard and pointer input
With a mouse or touch, pressing a key starts the note. With Sustain off, releasing it or leaving the key ends it.
The computer keyboard works too. The 14 white keys are a s d f g h j k l ; z x c v and the 10 black keys are w e t y u o p [ ] \ . Key repeat is ignored.
Guitar: Karplus-Strong synthesis
The guitar's six strings are tuned, from low to high, to E2 (82.41 Hz), A2 (110 Hz), D3 (146.83 Hz), G3 (196 Hz), B3 (246.94 Hz) and E4 (329.63 Hz). It uses no OscillatorNode. Each pluck is written into an AudioBuffer with the Karplus-Strong method and played with an AudioBufferSourceNode.
The buffer is 2.5 seconds long (DECAY_TIME). The first round(sampleRate / frequency) samples are random noise from -1 to 1, and every later sample is 0.996 × 0.5 × (the sample one period earlier + the sample after it).
function createKarplusStrong(ctx: AudioContext, frequency: number, duration: number) {
const sampleRate = ctx.sampleRate
const bufferSize = Math.round(sampleRate / frequency)
const totalSamples = Math.round(sampleRate * duration)
const audioBuffer = ctx.createBuffer(1, totalSamples, sampleRate)
const data = audioBuffer.getChannelData(0)
// Initialize with noise burst
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1
}
// Karplus-Strong: average adjacent samples with decay
const dampening = 0.996
for (let i = bufferSize; i < totalSamples; i++) {
data[i] = dampening * 0.5 * (data[i - bufferSize] + data[i - bufferSize + 1])
}
return audioBuffer
}Guitar: filter, gain and strumming
The sound first goes through a lowpass BiquadFilterNode with a cutoff of 2000 + 3 × the string frequency in Hz and Q = 1. The GainNode after it starts at 0.35 and ramps exponentially to 0.001 over 2.5 seconds.
Pressing a string plucks it, and moving onto another string while still pressing plucks that string too. A string sounds at most once per drag. There is no fixed delay between strings: the gap follows how fast the hand moves. The on-screen vibration of a plucked string ends after 2000 milliseconds.
const { freq } = STRINGS[index]
// Karplus-Strong synthesis for realistic guitar sound
const buffer = createKarplusStrong(ctx, freq, DECAY_TIME)
const source = ctx.createBufferSource()
source.buffer = buffer
// Shape the sound
const gain = ctx.createGain()
gain.gain.setValueAtTime(0.35, ctx.currentTime)
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + DECAY_TIME)
// Low-pass filter for warmth
const filter = ctx.createBiquadFilter()
filter.type = 'lowpass'
filter.frequency.value = 2000 + freq * 3
filter.Q.value = 1
source.connect(filter)
filter.connect(gain)
gain.connect(ctx.destination)
source.start(ctx.currentTime)
source.stop(ctx.currentTime + DECAY_TIME)Kalimba: two oscillators and their envelopes
Each kalimba note uses two oscillators: a triangle at the note frequency and a sine at twice the frequency, the second harmonic.
The triangle's gain rises linearly from 0 to 0.3 in 0.01 seconds, then ramps exponentially to 0.001 by 1.2 seconds. The sine rises to 0.08 in 0.01 seconds and ramps to 0.001 by 0.6 seconds. The two oscillators stop at 1.2 and 0.6 seconds.
// Triangle wave for kalimba-like tone
const osc = ctx.createOscillator()
osc.type = 'triangle'
osc.frequency.setValueAtTime(note.freq, ctx.currentTime)
// Second harmonic for richer tone
const osc2 = ctx.createOscillator()
osc2.type = 'sine'
osc2.frequency.setValueAtTime(note.freq * 2, ctx.currentTime)
// Envelope: gentle attack, natural decay
const gain = ctx.createGain()
gain.gain.setValueAtTime(0, ctx.currentTime)
gain.gain.linearRampToValueAtTime(0.3, ctx.currentTime + 0.01)
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 1.2)
const gain2 = ctx.createGain()
gain2.gain.setValueAtTime(0, ctx.currentTime)
gain2.gain.linearRampToValueAtTime(0.08, ctx.currentTime + 0.01)
gain2.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.6)
osc.connect(gain)
gain.connect(ctx.destination)
osc2.connect(gain2)
gain2.connect(ctx.destination)
osc.start(ctx.currentTime)
osc.stop(ctx.currentTime + 1.2)
osc2.start(ctx.currentTime)
osc2.stop(ctx.currentTime + 0.6)Kalimba: tuning, layout and the automatic melody
The kalimba has 8 tines tuned to C4 (261.63 Hz), D4 (293.66 Hz), E4 (329.63 Hz), G4 (392 Hz), A4 (440 Hz), C5 (523.25 Hz), D5 (587.33 Hz) and E5 (659.25 Hz). There is no F and no B.
The lowest note sits in the centre, and higher notes alternate left and right outward. By note index, the display order is 7, 5, 3, 1, 0, 2, 4, 6.
The automatic play button plays a 14-note melody, one note every 200 milliseconds.
The site's interface sounds, and the mute setting
Apart from the instruments, the site's interface sounds (pop, click, whoosh, ding, buzz) are short WAV files played with Howler.js through the site's own useSound hook. They are files, not waveforms built with the Web Audio API.
The site-wide sound setting is muted until the visitor turns sound on. Of the three instruments, the kalimba follows that setting and plays nothing while muted. Piano and Guitar do not read it.
Further reading
The MDN Web Audio API reference covers AudioContext and the nodes used here. The library behind the interface sounds is Howler.js.
Go deeper on this topic
Web Audio & Sound Programming
Audio synthesis, instrument implementation, and physics simulation references
Article 2 of 3 in this series.
Next reads
Three Books That Shaped My Physics Simulations — The Knowledge Behind 203 Implementations
The physics and math knowledge behind 203 interactive demos came primarily from three books. A concrete look at which chapters informed which implementations.
Audio Programming References — Where Web Audio API Meets Music Theory
Key insights from implementing 11 music components including Piano, Guitar, and Theremin with Web Audio API, plus a curated list of books and resources for audio programming.
Use the topic hub as a map, then continue to the next article in the series. New here? Start at the home hub →
FAQ
How does the piano demo compute its frequencies?
With 12-tone equal temperament from C4 = 261.63 Hz: with semitone counted from C4, the frequency is 261.63 times 2 to the power of semitone / 12. It covers 24 keys from C4 to B5.
Why does the guitar demo not use an oscillator?
Because it uses Karplus-Strong synthesis. The first period is filled with random noise, every later sample is 0.996 × 0.5 × (the sample one period earlier + the next one), and the 2.5 second AudioBuffer plays through a lowpass filter and a decaying GainNode.
Why does the kalimba sound different from the piano?
The kalimba layers a sine at twice the frequency over a triangle at the note frequency. Both rise in 0.01 seconds and then decay immediately: the triangle stops at 1.2 seconds and the sine at 0.6 seconds. The piano uses one triangle that rises to a gain of 0.25 and holds there while the key is down.