Three.js Piano Visualizer (Playable 3D Keyboard)

A playable 3D piano in Three.js covering G3 to C6, with hinged keys, falling note bars, pitch-coloured particle bursts, autoplay of public-domain melodies, and computer-keyboard or click input through Web Audio.

Key topics: piano visualizer, 3d piano, web audio synth, music visualization, three.js keyboard, midi

What this code does

- Keyboard: white and black keys are boxes whose origin sits at the back edge, so rotating them on x hinges them like real keys.
- Pitch: MIDI note → frequency via 440·2^((m−69)/12); the timbre is a triangle wave plus a soft octave partial with fast decay.
- Note Bars: scheduled notes fall toward their key, reaching it at note-on, with bar length equal to duration.
- Colour: pitch class (C, C♯, D…) maps to hue, so octaves share colours and chords form recognisable palettes.
- Input: keys A W S E D F T G Y H U J K play C4 upward, or click keys directly; autoplay schedules ahead on the audio clock.
- Controls: song, autoplay, tempo, left-hand bass and particles.

Continue Learning

JavaScript Implementation

ES6+
// Playable keyboard: map computer keys to MIDI notes, synthesise a short decaying tone
const mtof = (m) => 440 * 2 ** ((m - 69) / 12)
const keymap = { a: 60, w: 61, s: 62, e: 63, d: 64, f: 65, g: 67, h: 69, j: 71, k: 72 }
window.addEventListener('keydown', (e) => {
  const m = keymap[e.key]; if (!m) return
  const osc = ctx.createOscillator(), g = ctx.createGain()
  osc.type = 'triangle'; osc.frequency.value = mtof(m)
  g.gain.setValueAtTime(0.25, ctx.currentTime); g.gain.setTargetAtTime(0, ctx.currentTime, 0.4)
  osc.connect(g).connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + 2)
  keyMeshes[m].rotation.x = 0.07                          // press the 3D key
})