Skip to content

Instantly share code, notes, and snippets.

@atilafm
Forked from felippe-regazio/piano.js
Created August 23, 2023 17:42
Show Gist options
  • Save atilafm/a410f91aa49539ac87287d73ed6d218b to your computer and use it in GitHub Desktop.
Save atilafm/a410f91aa49539ac87287d73ed6d218b to your computer and use it in GitHub Desktop.
Turns your keyboard into a Piano
/*
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