Skip to content

Enumerating Ports

MIDIAccess.inputs and MIDIAccess.outputs are stable ReadonlyMap instances: the same map object is mutated in place as devices connect and disconnect. You never need to re-call requestMIDIAccess.

import { requestMIDIAccess } from "react-native-midi-api";
const midi = await requestMIDIAccess();
console.log("Inputs:");
for (const [id, input] of midi.inputs) {
console.log(` ${id}: ${input.name} (${input.manufacturer})`);
}
console.log("Outputs:");
for (const [id, output] of midi.outputs) {
console.log(` ${id}: ${output.name} (${output.manufacturer})`);
}

Devices connecting or disconnecting fire a statechange event on MIDIAccess. Assign onstatechange or use addEventListener:

// Handler style
midi.onstatechange = (event) => {
const { port } = event;
console.log(port?.name, port?.type, "", port?.state, port?.connection);
};
// EventTarget style
midi.addEventListener("statechange", (event) => {
// same event object
});

port.state is "connected" or "disconnected". port.connection is "open", "closed", or "pending".

Ports open automatically when you set onmidimessage (input) or call send() (output). Explicit control is available:

const input = [...midi.inputs.values()][0];
await input.open();
// ...
await input.close();

Each port also fires its own statechange event via port.onstatechange.