Connecting to MIDI output device

Once the hardware is connected, we can start writing code. First, let’s connect to the device programmatically.

Web MIDI API exposes navigator.requestMIDIAccess() method which returns a promise. The promise is resolved with a midiAccess object containing all the information about connected MIDI devices.

In the code above we take all the MIDI output devices by calling midiAccess.outputs.values() . It returns an iterator which can be used to obtain all our output. Then we can call Array.from to convert it into an array.

In my case the result is as following:

It can be slightly different based on your operating system and hardware used. In my case, the first interface is the operating system MIDI Through interface. Make sure you connect to the proper one (it’s UM-ONE MIDI 1 in my case).

Sending your first note

Once you find the output interface, you can use it to send MIDI notes. The interface exposed by the browser operates on low-level MIDI messages so we need to understand a little bit of how the MIDI commands are structured.

MIDI Protocol

MIDI 1.0 Specification is a collection of documents created throughout the years. The protocol consists of many different messages which can control after-touch, pitch bend, clock sync, reset signals and more. Today we will only need two of these messages though: noteOn and noteOff.

To communicate with a device we need to send proper command in an encoded form: usually as an 8, 16 or 24-bit message. Depending on a prefix the device knows which message it is. 1001 prefix is a noteOn event — indicating that the keyboard key has been pressed, 1000 is a noteOff event — indicating that the key has been depressed.

The next 4 bits encode MIDI Channel number. Each MIDI connection can control up to 16 independent channels at once — you can use it to control a few devices using a single connection or several channels in the single synthesizer (different voices for example).

The second octet represents the key we want to press (or depress). The middle C has a value of 60 and each semitone increases this value by one. The following diagram visualizes which MIDI note values correspond with which notes. The values can go up to 128.