Sling Academy
Home/JavaScript/Send and Receive MIDI Messages Using JavaScript Web MIDI

Send and Receive MIDI Messages Using JavaScript Web MIDI

Last updated: December 13, 2024

The Web MIDI API is an exciting feature that now allows developers to access MIDI devices directly from web applications using JavaScript. Whether you're interested in creating a musical instrument, a sequencer, or even a MIDI controller, the Web MIDI API provides the tools to interact with MIDI hardware seamlessly. In this article, we will explore how to send and receive MIDI messages using JavaScript.

Introduction to MIDI and the Web MIDI API

MIDI stands for Musical Instrument Digital Interface, which is a technical standard that describes a protocol, digital interface, and connectors to interconnect and communicate between a wide variety of electronic musical instruments, computers, and related devices.

The Web MIDI API is a JavaScript API that allows web applications to interact with MIDI devices. With the Web MIDI API, you can connect your web application to MIDI input and output devices, send and receive messages, and control MIDI hardware instruments.

Setting Up the Environment

To start working with MIDI in JavaScript, you'll need a modern browser that supports the Web MIDI API. As of the recent technology, browsers like Chrome and Edge provide good support for these features.

Basic Setup Code

Let's set up a simple environment to explore the Web MIDI API:

if (navigator.requestMIDIAccess) {
  navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
} else {
  alert("Your browser does not support the Web MIDI API.");
}

function onMIDISuccess(midiAccess) {
  console.log("MIDI Access Object:", midiAccess);
}

function onMIDIFailure() {
  console.log("Failed to get MIDI access - Your browser may not support it.");
}

The function navigator.requestMIDIAccess() returns a promise that resolves upon successfully gaining MIDI access, allowing you to handle connections in the onMIDISuccess function.

Receiving MIDI Messages

To receive MIDI messages, you'll need to iterate over the inputs provided by the MIDI access object and attach event listeners to them:

function onMIDISuccess(midiAccess) {
  for (let input of midiAccess.inputs.values()) {
    input.onmidimessage = handleMIDIMessage;
  }
}

function handleMIDIMessage(message) {
  const [status, data1, data2] = message.data;
  console.log(`Received MIDI Message: Status: ${status}, Data1: ${data1}, Data2: ${data2}`);
}

The handleMIDIMessage function is triggered each time a MIDI message is received, allowing you to parse the message data accordingly.

Sending MIDI Messages

To send MIDI messages, you will similarly access the available MIDI outputs and send messages as needed:

function sendMIDIMessage(outputId, status, data1, data2) {
  const outputs = Array.from(navigator.requestMIDIAccess().outputs);
  const output = outputs.find(out => out[0] === outputId)?.[1];

  output.send([status, data1, data2]);
}

const NOTE_ON = 0x90;
const NOTE_OFF = 0x80;
const middleC = 60;

// To play a note
sendMIDIMessage(outputId, NOTE_ON, middleC, 127);

// To stop a note later
setTimeout(() => sendMIDIMessage(outputId, NOTE_OFF, middleC, 0), 500);

This snippet demonstrates how to send a basic NOTE ON and NOTE OFF message to play a middle C note on your selected MIDI output.

Conclusion

The Web MIDI API opens up exciting possibilities for musical applications on the web. Whether for learning, education, professional music creation, or just personal projects, you can now create interactive and responsive MIDI applications with ease. By taking advantage of modern web standards, the possibilities are limited only by your imagination. Experiment with different MIDI devices, messages, and composition techniques to create your unique musical web application!

Next Article: Integrate Keyboards, Guitars, and Drums via the Web MIDI API in JavaScript

Previous Article: Access Musical Instruments and Controllers with the Web MIDI API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration