-
-
Save sc0ttj/ca5ee129f772a59e5fd4c1d6dfdf4cbb to your computer and use it in GitHub Desktop.
Simple web midi implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var OP1MidiInterface = function(midi) { | |
var data, cmd, channel, type, note, velocity; | |
midi.inputs.forEach(function(input) { | |
if (input.name.indexOf('OP-1') > -1) { | |
document.dispatchEvent(new Event('midi-connected')); | |
input.onmidimessage = onMIDIMessage; | |
} | |
}); | |
midi.onstatechange = onStateChange; | |
function onMIDIMessage(event) { | |
document.dispatchEvent(new Event('midi-activity')); | |
data = event.data, | |
cmd = data[0] >> 4, | |
channel = data[0] & 0xf, | |
type = data[0] & 0xf0, // channel agnostic | |
note = data[1], | |
velocity = data[2]; | |
switch (type) { | |
case 144: // noteOn | |
noteOn(note, velocity); | |
break; | |
case 128: // noteOff | |
noteOff(note, velocity); | |
break; | |
} | |
} | |
function onStateChange(event) { | |
var port = event.port, | |
state = port.state, | |
name = port.name, | |
type = port.type; | |
// if (type == "input") console.log("name", name, "port", port, "state", state); | |
if (name.indexOf('OP-1') > -1) { | |
document.dispatchEvent(new Event('midi-' + state)); | |
} | |
} | |
function noteOn(midiNote, velocity) { | |
document.dispatchEvent(new CustomEvent('midi-note-on', { 'detail': midiNote })); | |
} | |
function noteOff(midiNote, velocity) { | |
document.dispatchEvent(new CustomEvent('midi-note-off', { 'detail': midiNote })); | |
} | |
} | |
// Usage: | |
if (navigator.requestMIDIAccess) { | |
navigator.requestMIDIAccess({ sysex: false }).then(function(midi) { | |
new OP1MidiInterface(midi); | |
}, function(){}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment