当前位置: 首页 > 工具软件 > Piano-MIDI > 使用案例 >

web-midi-api

石正卿
2023-12-01
  1. MIDI (Musical Instrument Digital Interface)
  2. midi携带的信息:pitch, velocity (how loudly or softly a note is played), vibrato, volume, panning, modulation, and more
  3. midi 发送信息给daw :digital audio workstation convert the signals into written notation,

navigator.requestMIDIAccess()
4. request access to any MIDI devices (inputs or outputs) connected to your computer
5. The requestMIDIAccess() method returns a promise,so we need to establish success and failure callbacks.

if (navigator.requestMIDIAccess) {
    console.log('This browser supports WebMIDI!');
} else {
    console.log('WebMIDI is not supported in this browser.');
}

MIDIAccess
6. contains references to all available inputs (such as piano keyboards) and outputs (such as synthesizers).
7.

navigator.requestMIDIAccess()
    .then(onMIDISuccess, onMIDIFailure);

function onMIDISuccess(midiAccess) {
    console.log(midiAccess);
    var inputs = midiAccess.inputs;
    var outputs = midiAccess.outputs;
}

function onMIDIFailure() {
    console.log('Could not access your MIDI devices.');
}

MIDIMessageEvent

  1. inputs and outputs with a MIDIMessageEvent object.
  2. contain information about the MIDI event such as pitch, velocity (how softly or loudly a note is played), timing, and more.
  3. data array[144, 72, 64] `[what type of command was sent, note value, velocity]
    1. type of command
      144 signifies a “note on” event, and 128 typically signifies a “note off” event
    2. Note values
      Note values are on a range from 0–127,“middle C” is 60;88-key piano has a value of 21, and the highest note is 108.
    3. Velocity values
      a. range from 0–127 (softest to loudest). softest possible “note on” velocity is 1.
      b. A velocity of 0 is sometimes used in conjunction
function getMIDIMessage(message) {
    var command = message.data[0];
    var note = message.data[1];
    var velocity = (message.data.length > 2) ? message.data[2] : 0; // a velocity value might not be included with a noteOff command

    switch (command) {
        case 144: // noteOn
            if (velocity > 0) {
                noteOn(note, velocity);
            } else {
                noteOff(note);
            }
            break;
        case 128: // noteOff
            noteOff(note);
            break;
        // we could easily expand this switch statement to cover other types of commands such as controllers or sysex
    }
}


onmidimessage 监听输入

function onMIDISuccess(midiAccess) {
    for (var input of midiAccess.inputs.values())
        input.onmidimessage = getMIDIMessage;
    }
}

function getMIDIMessage(midiMessage) {
    console.log(midiMessage);
}

例子


参考:
https://www.smashingmagazine.com/2018/03/web-midi-api/

 类似资料: