Skip to content

Instantly share code, notes, and snippets.

@felippe-regazio
Last active October 6, 2023 05:59
Show Gist options
  • Save felippe-regazio/3426fef266be11197c9e00326edab3ba to your computer and use it in GitHub Desktop.
Save felippe-regazio/3426fef266be11197c9e00326edab3ba 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);
});
@Guiqft
Copy link

Guiqft commented Aug 23, 2023

Seems like line 30 does nothing.

playing[x].disconnect;

@felippe-regazio
Copy link
Author

Seems like line 30 does nothing.

playing[x].disconnect;

Thanks. Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment