Building a Piano in the Browser: From Keyboard Input to Musical Frequency

2026-12-04来源 dev.toEnglish

Building a Piano in the Browser: From Keyboard Input to Musical Frequency

Have you ever wondered how complex it is to build a responsive, polyphonic musical instrument using vanilla JavaScript and modern browser APIs?

A lot of developers assume that creating a playable web piano requires heavy third-party gaming frameworks or WebAssembly engines. In reality, modern browser primitives—specifically the Web Audio API and DOM pointer events—provide everything necessary to build a lightning-fast keyboard with under 15ms of latency.

In this tutorial, we will build a polyphonic browser piano engine from scratch:

Mapping computer keyboard inputs to musical pitches
Calculating equal temperament frequencies mathematically
Managing low-latency polyphonic voice triggering
Designing a clean visual keyboard in CSS

  1. Step 1: Mapping Computer Keys to Musical Pitches

To allow users to play immediately using their laptop keyboard, we can map the QWERTY keyboard's home row to white piano keys, and the row above it to black accidentals:

// Key mapping: QWERTY key code -> Standard MIDI Note Number // Middle C (C4) is MIDI note 60 const KEY_MAP: Record<string, number> = { // White Keys 'KeyA': 60, // C4 'KeyS': 62, // D4 'KeyD': 64, // E4 'KeyF': 65, // F4 'KeyG': 67, // G4 'KeyH': 69, // A4 (Concert Pitch 440 Hz) 'KeyJ': 71, // B4 'KeyK': 72, // C5 // Black Keys (Accidentals) 'KeyW': 61, // C#4 / Db4 'KeyE': 63, // D#4 / Eb4 'KeyT': 66, // F#4 / Gb4 'KeyY': 68, // G#4 / Ab4 'KeyU': 70, // A#4 / Bb4 }; 
  1. Step 2: Synthesizing the Audio Voice

While production applications often use high-resolution acoustic samples, you can synthesize rich musical tones directly using Web Audio's native OscillatorNode with an exponential decay envelope:

class SynthVoice { private ctx: AudioContext; constructor(ctx: AudioContext) { this.ctx = ctx; } public trigger(frequency: number, durationSeconds: number = 1.5): void { const osc = this.ctx.createOscillator(); const gain = this.ctx.createGain(); // A triangle wave offers warm, harmonic character similar to a wooden tone osc.type = 'triangle'; osc.frequency.setValueAtTime(frequency, this.ctx.currentTime); // Exponential gain decay mimics acoustic piano string dampening const now = this.ctx.currentTime; gain.gain.setValueAtTime(0.001, now); gain.gain.exponentialRampToValueAtTime(0.4, now + 0.02); // 20ms attack gain.gain.exponentialRampToValueAtTime(0.0001, now + durationSeconds); // Decay osc.connect(gain); gain.connect(this.ctx.destination); osc.start(now); osc.stop(now + durationSeconds); } } 
  1. Step 3: Polyphony and Preventing Key Repeat Glitches

When a user holds down a key on a physical keyboard, the operating system's accessibility daemon triggers repeated keydown events (e.g., aaaaaaaa). In a music tool, this causes machine-gun re-triggering.

We solve this by maintaining an active Set of currently depressed keys:

const activeKeys = new Set<string>(); const audioCtx = new AudioContext(); const synth = new SynthVoice(audioCtx); window.addEventListener('keydown', (e) => { // Prevent repeating key events when key is held down if (e.repeat || activeKeys.has(e.code)) return; const midi = KEY_MAP[e.code]; if (midi) { activeKeys.add(e.code); // Unlock browser audio context if suspended if (audioCtx.state === 'suspended') { audioCtx.resume(); } // Convert MIDI to frequency: f = 440 * 2^((midi - 69) / 12) const freq = 440 * Math.pow(2, (midi - 69) / 12); synth.trigger(freq); highlightKeyUI(midi, true); } }); window.addEventListener('keyup', (e) => { if (activeKeys.has(e.code)) { activeKeys.delete(e.code); const midi = KEY_MAP[e.code]; if (midi) { highlightKeyUI(midi, false); } } }); 
  1. Step 4: Styling the Keyboard Layout

In CSS, keyboard layouts use absolute positioning for black keys over flexible white keys:

.piano-keyboard { display: flex; position: relative; user-select: none; } .white-key { width: 44px; height: 180px; background: #ffffff; border: 1px solid #d1d5db; border-radius: 0 0 4px 4px; cursor: pointer; } .white-key.active { background: #e5e7eb; } .black-key { position: absolute; width: 28px; height: 110px; background: #111827; border-radius: 0 0 3px 3px; z-index: 2; cursor: pointer; } .black-key.active { background: #374151; } 

Production Considerations: Samples vs. Synthesis

While pure mathematical oscillators are easy to write, an authentic piano experience requires multi-sampled acoustic recordings (capturing real felt hammer strikes, string overtones, and wood resonance).

If you are interested in testing a production-grade Web Audio implementation that streams real acoustic Grand Piano sample banks across a complete 88-key range with A440 tuning and metronome tools, feel free to explore our live open web project, [Free Piano Tool][https://www.freepianotool.com/]

Happy coding, and have fun building in the browser!

原文:https://www.a8q9.cn/en/article/building-a-piano-in-the-browser-from-keyboard-input-to-musical-frequency-6a0f04.html

相关文章