Skip to content

Instantly share code, notes, and snippets.

@surma
Last active October 31, 2016 13:33
Show Gist options
  • Save surma/7d7c80524af77e9410cfc84e1f42d7ab to your computer and use it in GitHub Desktop.
Save surma/7d7c80524af77e9410cfc84e1f42d7ab to your computer and use it in GitHub Desktop.
Stupid MIDI synthisizer
<script>
// 5 octaves + 9 semitones under A440Hz is Midi Key Zero
const MidiKeyZero = 440/(Math.pow(2, 5) * Math.pow(2, 9/12)) ;
const ctx = new AudioContext();
const oscis = new Map();
const volumeCtrl = ctx.createGain();
volumeCtrl.gain.value = 0;
volumeCtrl.connect(ctx.destination);
function processMidiEvent(event) {
console.log(event.data);
switch (event.data[0]) {
case 0x90: // Note On
if (oscis.has(event.data[1]))
return;
const osci = ctx.createOscillator();
osci.frequency.value = MidiKeyZero * Math.pow(2, event.data[1]/12);
osci.connect(volumeCtrl);
osci.start();
oscis.set(event.data[1], osci);
break;
case 0x80: // Note Off
if(oscis.has(event.data[1]))
oscis.get(event.data[1]).disconnect();
oscis.delete(event.data[1]);
break;
case 0xB0: // Sliders
volumeCtrl.gain.value = event.data[2] / 128;
}
}
navigator.requestMIDIAccess()
.then(ma => ma.inputs.forEach(input => input.onmidimessage = processMidiEvent));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment