The Web MIDI API connects to and interacts with Musical Instrument Digital Interface (MIDI) Devices.
The interfaces deal with the practical aspects of sending and receiving MIDI messages. Therefore, the API can be used for musical and non-musical uses, with any MIDI device connected to your computer.
The user must explicitly grant permission to use the API through a user-agent specific mechanism, or have previously granted permission. Note that if access is denied by a permission policy it cannot be granted by a user permission.
The permission status can be queried using the Permissions API method navigator.permissions.query(), passing a permission descriptor with the midi permission and (optional) sysex property:
js
navigator.permissions.query({name:"midi",sysex:true}).then((result)=>{if(result.state ==="granted"){// Access granted.}elseif(result.state ==="prompt"){// Using API will prompt for permission}// Permission was denied by user prompt or permission policy});
Examples
Gaining access to the MIDI port
The navigator.requestMIDIAccess() method returns a promise that resolves to a MIDIAccess object, which can then be used to access a MIDI device. The method must be called in a secure context.
js
let midi =null;// global MIDIAccess objectfunctiononMIDISuccess(midiAccess){
console.log("MIDI ready!");
midi = midiAccess;// store in the global (in real usage, would probably keep in an object instance)}functiononMIDIFailure(msg){
console.error(`Failed to get MIDI access - ${msg}`);}
navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
Listing inputs and outputs
In this example the list of input and output ports are retrieved and printed to the console.
js
functionlistInputsAndOutputs(midiAccess){for(const entry of midiAccess.inputs){const input = entry[1];
console.log(`Input port [type:'${input.type}']`+` id:'${input.id}'`+` manufacturer:'${input.manufacturer}'`+` name:'${input.name}'`+` version:'${input.version}'`,);}for(const entry of midiAccess.outputs){const output = entry[1];
console.log(`Output port [type:'${output.type}'] id:'${output.id}' manufacturer:'${output.manufacturer}' name:'${output.name}' version:'${output.version}'`,);}}
Handling MIDI Input
This example prints incoming MIDI messages on a single port to the console.
js
functiononMIDIMessage(event){let str =`MIDI message received at timestamp ${event.timeStamp}[${event.data.length} bytes]: `;for(const character of event.data){
str +=`0x${character.toString(16)}`;}
console.log(str);}functionstartLoggingMIDIInput(midiAccess, indexOfPort){
midiAccess.inputs.forEach((entry)=>{
entry.onmidimessage = onMIDIMessage;});}