Parse and interpret Web MIDI API input message data
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: