Skip to content

Instantly share code, notes, and snippets.

@bryc
Created December 15, 2016 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryc/9539e5c5488780d5db551aefb0952777 to your computer and use it in GitHub Desktop.
Save bryc/9539e5c5488780d5db551aefb0952777 to your computer and use it in GitHub Desktop.
function noteFromKey(keyCode) {
var char = String.fromCharCode(keyCode).toUpperCase();
if(pianoMap[char]) {
return pianoMap[char];
}
else {
return false;
}
}
/*
"c4" : 260.74,
"c#4": 278.44,
"d4" : 293.33,
"d#4": 309.03,
"e4" : 330.00,
"f4" : 347.65,
"f#4": 371.25,
"g4" : 391.11,
"g#4": 417.66,
"a4" : 440.000,
"a#4": 463.54,
"b4" : 495.00,
"c5" : 521.48,
*/
var pianoMap = {
"Z": 260.74, // C-4
"S": 278.44, // #
"X": 293.33, // D-4
"D": 309.03, // #
"C": 330.00, // E-4
"V": 347.65, // F-4
"G": 371.25, // #
"B": 391.11, // G-4
"H": 417.66, // #
"N": 440.00, // A-4
"J": 463.54, // #
"M": 495.00, // B-4
"Q": 521.48, // C-5
};
// declare our objects ----
var ctx = new AudioContext();
var osc = ctx.createOscillator();
var amp = ctx.createGain();
// configure properties ----
amp.gain.value = 0;
// connect objects ----
osc.connect(amp);
amp.connect(ctx.destination);
// start oscillator ----
osc.start();
// ----------------
// key events ----
window.onkeydown = function(e) {
var key = noteFromKey(e.keyCode);
if(!key) {return;}
console.log(osc,key);
osc.frequency.setValueAtTime(key, osc.context.currentTime);
amp.gain.value = .01;
};
window.onkeyup = function() {
amp.gain.value = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment