Let's assume I'm already using the Web MIDI API to listen on MIDI inputs for messages, and now I'm trying to understand and make use of the data I'm receiving.
How can I parse some basic information out of a MIDIMessageEvent
?
How might I interpret the parsed information for some basic MIDI events?
Examples written in ES6.
The data
in a MIDIMessageEvent
can be split up with a parsing function like this:
/**
* Parse basic information out of a MIDI message.
*/
function parseMidiMessage(message) {
return {
command: message.data[0] >> 4,
channel: message.data[0] & 0xf,
note: message.data[1],
velocity: message.data[2] / 127
}
}
Given some event functions for handling basic MIDI events:
function onNote(note, velocity) {}
function onPad(pad, velocity) {}
function onPitchBend(value) {}
function onModWheel(value) {}
We might use the parsing function from above to interpret through MIDI messages and call for the above event functions:
/**
* Handle a MIDI message from a MIDI input.
*/
function handleMidiMessage(message) {
// Parse the MIDIMessageEvent.
const {command, channel, note, velocity} = parseMidiMessage(message)
// Stop command.
// Negative velocity is an upward release rather than a downward press.
if (command === 8) {
if (channel === 0) onNote(note, -velocity)
else if (channel === 9) onPad(note, -velocity)
}
// Start command.
else if (command === 9) {
if (channel === 0) onNote(note, velocity)
else if (channel === 9) onPad(note, velocity)
}
// Knob command.
else if (command === 11) {
if (note === 1) onModWheel(velocity)
}
// Pitch bend command.
else if (command === 14) {
onPitchBend(velocity)
}
}
The handler is attached to the correct MIDI input(s):
midiInput.onmidimessage = handleMidiMessage
Resources: