Skip to content

Instantly share code, notes, and snippets.

@Belrestro
Last active July 12, 2018 07:26
Show Gist options
  • Save Belrestro/7d6526d7894e83f9f371d80669559955 to your computer and use it in GitHub Desktop.
Save Belrestro/7d6526d7894e83f9f371d80669559955 to your computer and use it in GitHub Desktop.
oscillator experiment
(() => {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const noteMap = {
'90': {
key: 'Z',
note: 'C',
freq: 261.63
},
'83': {
key: 'S',
note: 'C#',
freq: 277.18
},
'88': {
key: 'X',
note: 'D',
freq: 293.66
},
'68': {
key: 'D#',
note: 'C',
freq: 311.13
},
'67': {
key: 'E',
note: 'C',
freq: 329.63
},
'86': {
key: 'V',
note: 'F',
freq: 349.23
},
'71': {
key: 'G',
note: 'F#',
freq: 369.99
},
'66': {
key: 'G',
note: 'F',
freq: 392.00
},
'72': {
key: 'H',
note: 'G#',
freq: 415.30
},
'78': {
key: 'N',
note: 'A',
freq: 440.00
},
'74': {
key: 'J',
note: 'A#',
freq: 466.16
},
'77': {
key: 'B',
note: 'F',
freq: 493.88
},
'188': {
key: ',',
note: 'C',
freq: 523.25
},
};
const pressedKeys = {};
const createOscillator = (noteObject) => {
const oscillator = audioCtx.createOscillator();
oscillator.frequency.setValueAtTime(noteObject.freq, audioCtx.currentTime); // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
return oscillator;
}
const playNote = (e) => {
const {keyCode} = e;
const avilableKeys = Object.keys(noteMap);
const inNoteMap = avilableKeys.some(key => key == keyCode);
const inPressedKeys = pressedKeys[keyCode];
if (inNoteMap && !inPressedKeys) {
const noteObject = noteMap[keyCode];
pressedKeys[keyCode] = createOscillator(noteObject);
}
}
const stopNote = (e) => {
const {keyCode} = e;
const avilableKeys = Object.keys(noteMap);
const inNoteMap = avilableKeys.some(key => key == keyCode);
if (inNoteMap) {
const oscillator = pressedKeys[keyCode];
oscillator.stop();
delete pressedKeys[keyCode];
}
}
document.body.addEventListener('keydown', playNote);
document.body.addEventListener('keyup', stopNote);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment