- a developer's blog

Connecting Midi Device to Browser with the Web MIDI API & Web Audio API

Web MIDI API + Web Audio API = A killer combo !

We live in exciting times. Browsers are equipped with the Web MIDI API specification which lets us manipulate and access MIDI Interface devices to communicate with the browser over hardware MIDI ports or even USB ports for devices that support USB-MIDI.

The icing on the cake – browsers are also equipped with the Web Audio API that allows us to add audio effects, build audio visualizations, add spatial effects and much more.

These two APIs opens ups all kinds of avenues for music producers to explore. Time to say good bye to expensive hardware like music synthesizers, hardware drum pads, show light systems or any other mechanical MIDI devices. Not just the hardware, its also time to bid adieu to those expensive WYSIAYG (What you see is all you get) digital audio work stations.

It’s all there in your browser !

Here’s how you can connect your MIDI device to the browser.

Note: This code assumes you have a MIDI device that can communicate over the MIDI port. If you are instead interested in controlling MIDI with your mouse and keyboard, here’s an excellent article.

To see the below code in action, connect a MIDI device and refresh this page. Then click on the result tab in the below embed. Your MIDI device should have connected and responding!

Code Explanation

The MIDI access starts with a call to

`navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);`

This calls the callback function onMIDISuccess, if a MIDI device is found. This function loops over all available inputs and listen for any MIDI input.

The midi message is converted to frequency and this is passed through an OscillatorNode and a GainNode.
The oscillator node creates a sine wave while the gain node takes care of magnifying the wave based on the velocity of the MIDI input. The OscillatorNode and the GainNode are typical examples of node of a Web Audio Graph.

The Web Audio API is based around the central idea of a graph of basic audio operations. Each node in the graph represents some Audio processing. So we have two nodes in our example – the OscillatorNode and the GainNode. All the nodes exist in an audio context which is created in the first few lines with the following code.

 var audio_context = window.AudioContext || window.webkitAudioContext;
 var con = new audio_context();
 var osc = con.createOscillator();
 var gain_node = con.createGain();
 osc.frequency.value = 0;

So there you have a functional MIDI synthesizer in your browser.