最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to parse Web MIDI API input messages (onmidimessage) - Stack Overflow

programmeradmin6浏览0评论

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?

  • mand
  • channel
  • note
  • velocity

How might I interpret the parsed information for some basic MIDI events?

  • onNote
  • onPad
  • onPitchBend
  • onModWheel

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?

  • mand
  • channel
  • note
  • velocity

How might I interpret the parsed information for some basic MIDI events?

  • onNote
  • onPad
  • onPitchBend
  • onModWheel
Share Improve this question edited Dec 1, 2016 at 4:57 ChaseMoskal asked Dec 1, 2016 at 4:50 ChaseMoskalChaseMoskal 7,6917 gold badges41 silver badges56 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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 {
    mand: 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 {mand, channel, note, velocity} = parseMidiMessage(message)

  // Stop mand.
  // Negative velocity is an upward release rather than a downward press.
  if (mand === 8) {
    if      (channel === 0) onNote(note, -velocity)
    else if (channel === 9) onPad(note, -velocity)
  }

  // Start mand.
  else if (mand === 9) {
    if      (channel === 0) onNote(note, velocity)
    else if (channel === 9) onPad(note, velocity)
  }

  // Knob mand.
  else if (mand === 11) {
    if (note === 1) onModWheel(velocity)
  }

  // Pitch bend mand.
  else if (mand === 14) {
    onPitchBend(velocity)
  }
}

The handler is attached to the correct MIDI input(s):

midiInput.onmidimessage = handleMidiMessage

Resources:

  • Web MIDI API
  • MIDI message data summary
  • Script by cwilso
  • Script by cotejp
发布评论

评论列表(0)

  1. 暂无评论