Sling Academy
Home/JavaScript/Integrate Keyboards, Guitars, and Drums via the Web MIDI API in JavaScript

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

Last updated: December 13, 2024

The Web MIDI API is a flexible way to enable musicians to connect their keyboards, guitars, and drum kits to web applications. Through this, musicians can extend their musical setups, create web-based music interfaces, and experiment with new forms of interactive artwork. In this step-by-step guide, we will dive into integrating various musical instruments into a web application using the Web MIDI API in JavaScript.

Getting Started with Web MIDI API

Before you start coding, ensure your browser supports the Web MIDI API. Most modern browsers, like Chrome and Edge, do, while others like Firefox might still be on the way.

Requesting MIDI Access

The first step is to request access to the MIDI devices. This involves calling the navigator.requestMIDIAccess method. This returns a promise that resolves to a MIDIAccess object, giving you control over MIDI input and output devices.

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

function onMIDISuccess(midiAccess) {
    console.log('MIDI Access Object', midiAccess);
    const inputs = midiAccess.inputs;
    const outputs = midiAccess.outputs;
}

function onMIDIFailure(error) {
    console.error('Error accessing MIDI devices:', error);
}

Here, onMIDISuccess is called if the promise resolves successfully and onMIDIFailure if it fails.

Handling MIDI Inputs

MIDI devices such as keyboards typically send messages that could be anything from note-on/note-off signals to control change updates. You can listen for these messages on inputs in the following way:

function onMIDISuccess(midiAccess) {
    midiAccess.inputs.forEach((midiInput) => {
        midiInput.onmidimessage = handleMIDIMessage;
    });
}

function handleMIDIMessage(event) {
    const data = event.data;
    const [command, note, velocity] = data;
    console.log(`Command: ${command}, Note: ${note}, Velocity: ${velocity}`);
}

Above, every event carries the data property containing the MIDI message.

Connecting Guitars and Drums

For instruments like digital guitars and electronic drum kits, the integration is similarly straightforward. These instruments often follow the MIDI standard messages, allowing seamless connection much like keyboards.

Mapping Input Messages

Most digital guitars and drums send specific messages for their various signals. For example, you might receive different note-on messages for different drum pads or strings struck on a digital guitar. Handling such varieties involves recognizing the specific inputs using the same handleMIDIMessage function while possibly mapping actions differently.

function handleMIDIMessage(event) {
    const data = event.data;
    const [command, note, velocity] = data;

    if (command === 144) { // Note on message
        console.log(`Note On: ${note} with velocity ${velocity}`);
    } else if (command === 128) { // Note off message
        console.log(`Note Off: ${note}`);
    }
}

Outputting MIDI Messages

Beyond just reading from these instruments, your web application can also output to MIDI devices. This means your application can play notes back on connected devices, change settings or even control connected synthesizers. Here’s how you can send a message:

function sendMIDIMessage(output, command, note, velocity) {
    const message = [command, note, velocity];
    console.log(`Sending MIDI Message: ${message}`);
    output.send(message);
}

Using the above function requires an output device from the outputs collection of your MIDIAccess object.

Real-World Use Cases

With all the pieces in place to communicate between instruments and the web browser, countless opportunities open up. Whether you’re building an educational app that visualizes scales for guitar learners or a drum loop generator, harness the Web MIDI API for its extensive capabilities.

Final Thoughts

The Web MIDI API offers a direct line between traditional musical expressiveness and the dynamic web environment. By enabling real-time control of musical elements via JavaScript, developers can foster creativity among musicians and hobbyists in fascinating new contexts.

Building music applications or features using the Web MIDI API necessitates understanding your target instruments' MIDI message specifics and harnessing creativity to extend your project features meaningfully.

Next Article: Create Interactive Music Apps Using JavaScript Web MIDI

Previous Article: Send and Receive MIDI Messages Using JavaScript Web MIDI

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