-
-
Save atilafm/a410f91aa49539ac87287d73ed6d218b to your computer and use it in GitHub Desktop.
Turns your keyboard into a Piano
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Put this code on a page or paste on your console, then focus on the page | |
and try to press keys from q...p and a...l | |
*/ | |
const getKeyFrequency = n => Math.pow(2, (n - 49) / 12) * 440; | |
const audioCtx = new AudioContext(); | |
const playing = {}; | |
window.addEventListener('keydown', e => { | |
'qawsedrftgyhujikolp'.split('').forEach((k, i) => { | |
if (e.key === k && !playing[k]) { | |
const frequency = getKeyFrequency(30 + i); | |
const oscillator = audioCtx.createOscillator(); | |
playing[k] = oscillator; | |
oscillator?.frequency.setValueAtTime(frequency, audioCtx.currentTime); | |
oscillator.connect(audioCtx.destination); | |
oscillator.type = "triangle"; | |
oscillator.start(); | |
} | |
}); | |
}); | |
window.addEventListener('keyup', e => { | |
const k = e.key; | |
const stop = x => { | |
try { | |
playing[x].stop(); | |
playing[x].disconnect; | |
playing[x] = false; | |
}catch{} | |
} | |
if (e.key === 'n') { | |
Object.keys(playing).forEach(x => stop(x)); | |
} | |
stop(k); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment