Sling Academy
Home/JavaScript/Create Interactive Music Apps Using JavaScript Web MIDI

Create Interactive Music Apps Using JavaScript Web MIDI

Last updated: December 13, 2024

With the evolution of web technologies, developing interactive music applications using simple scripting languages has become more accessible. JavaScript's Web MIDI API is one such technology that allows developers to communicate with Musical Instrument Digital Interface (MIDI) hardware. In this article, you'll learn how to utilize the Web MIDI API to create dynamic music projects right from your browser.

Understanding Web MIDI API

The Web MIDI API provides a standard way for web developers to interact with MIDI instruments over a browser. It simplifies the process of sending and receiving MIDI messages, which can be used for a variety of musical applications including games, music education platforms, and live performance tools.

Prerequisites

Before diving into coding, ensure you have a basic understanding of JavaScript and an up-to-date browser that supports the Web MIDI API. A MIDI device is required to test real interactions; if you don’t have one, virtual MIDI tools are available online.

Setting Up Web MIDI in JavaScript

Start by checking if your browser supports the Web MIDI API. This is crucial as not all browsers have implemented support for it yet:

if (navigator.requestMIDIAccess) {  
    console.log('Your browser supports Web MIDI API.');  
} else {  
    console.warn('Web MIDI API is not available in your browser.');  
}

If the API is available, you can request access to MIDI devices through the requestMIDIAccess method:

navigator.requestMIDIAccess().then(  
    (access) => {  
        console.log('MIDI Access Object', access);  
    },  
    (err) => {  
        console.error('MIDI access error:', err);  
    }  
);

Connecting and Listening to MIDI Devices

Once you have access, you’ll want to connect and listen to inputs from MIDI devices. Here's how you can implement it:

function onMIDIInit(midiAccess) {  
    const inputs = midiAccess.inputs;  
    inputs.forEach(input => {  
        input.onmidimessage = onMIDImessage;  
    });  
}

Handle incoming MIDI messages to perform an action, like displaying note data:

function onMIDImessage(message) {  
    const data = message.data;  
    console.log('MIDI data:', data);  
}

Generating Sound with MIDI Data

To play sound based on MIDI input, you can use the Web Audio API alongside the MIDI data. First, set up an audio context:

const audioContext = new (window.AudioContext || window.webkitAudioContext)();

You'll want to map MIDI note numbers to frequencies and play sound:

function playFrequency(noteNumber) {  
    // Convert MIDI note number to frequency using A440 temperate scale  
    const frequency = 440 * Math.pow(2, (noteNumber - 69) / 12);  
    const oscillator = audioContext.createOscillator();  
    oscillator.type = 'sine';  
    oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);  
    oscillator.connect(audioContext.destination);  
    oscillator.start();  
    oscillator.stop(audioContext.currentTime + 1); 
}

Invoke playFrequency method during the onmidimessage event using the note data received:

function onMIDImessage(message) {  
    const data = message.data;  
    const command = data[0];  
    const note = data[1];  
    if (command === 144) {  // Note on  
        playFrequency(note);  
    }  
}

Conclusion

Creating interactive music applications with Web MIDI and JavaScript can be a fun endeavor. Understanding this API allows you to leverage MIDI inputs and create rich, interactive musical experiences directly in-browser, providing new avenues for aspiring musicians and developers alike. Remember to experiment with various MIDI messages and explore the possibilities integrated with other web features such as 3D visualizations, machine learning libraries, and more.

Next Article: Transform Real-Time MIDI Input into Sound in JavaScript

Previous Article: Integrate Keyboards, Guitars, and Drums via 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