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 navigator.requestMIDIAccess()
method returns a promise that resolves to a MIDIAccess
, which can then be used to access a MIDI device. The method must be called in a secure context.
var midi = null;
function onMIDISuccess( midiAccess ) {
console.log( "MIDI ready!" );
midi = midiAccess;
}
function onMIDIFailure(msg) {
console.log( "Failed to get MIDI access - " + msg );
}
navigator.requestMIDIAccess().then( onMIDISuccess, onMIDIFailure );
In this example the list of input and output ports are retrieved and printed to the console.
function listInputsAndOutputs( midiAccess ) {
for (var entry of midiAccess.inputs) {
var input = entry[1];
console.log( "Input port [type:'" + input.type + "'] id:'" + input.id +
"' manufacturer:'" + input.manufacturer + "' name:'" + input.name +
"' version:'" + input.version + "'" );
}
for (var entry of midiAccess.outputs) {
var output = entry[1];
console.log( "Output port [type:'" + output.type + "'] id:'" + output.id +
"' manufacturer:'" + output.manufacturer + "' name:'" + output.name +
"' version:'" + output.version + "'" );
}
}
This example prints incoming MIDI messages on a single port to the console.
function onMIDIMessage( event ) {
var str = "MIDI message received at timestamp " + event.timeStamp + "[" + event.data.length + " bytes]: ";
for (var i=0; i<event.data.length; i++) {
str += "0x" + event.data[i].toString(16) + " ";
}
console.log( str );
}
function startLoggingMIDIInput( midiAccess, indexOfPort ) {
midiAccess.inputs.forEach( function(entry) {entry.onmidimessage = onMIDIMessage;});
}