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