// A MIDI keyboard, through Web MIDI: note-ons and note-offs from every // connected input (and ones plugged in later). export const midiSupported = () => typeof navigator !== 'undefined' && !!navigator.requestMIDIAccess; // Ask for MIDI access (the browser may ask the user), then call // onNote(note, on) for each key pressed (on) or released, // onPedal(down) when the sustain pedal goes down or up, onControl(channel, // controller, value) for every control change (a knob turned: value 0 to // 127), and onInputs(names) now and whenever a device is plugged in or out. export async function openMidi({ onNote, onPedal, onControl, onInputs }) { const access = await navigator.requestMIDIAccess(); const handle = (e) => { const [status, note, vel] = e.data; const type = status & 0xf0; if (type === 0x90 && vel > 0) onNote(note, true); else if (type === 0x80 || type === 0x90) onNote(note, false); else if (type === 0xb0) { if (note === 64) onPedal(vel >= 64); onControl(status & 0x0f, note, vel); } }; const hook = () => { const inputs = [...access.inputs.values()].filter((i) => i.state !== 'disconnected'); for (const input of inputs) input.onmidimessage = handle; onInputs(inputs.map((i) => i.name || 'MIDI input')); }; access.onstatechange = hook; hook(); return access; }