MIDI tutorial for programmers
MIDI is a protocol for describing performances, not a sound format. A keyboard does not send audio. It sends short messages such as “key 60 went down on channel 1, fairly hard”. Something else turns those messages into sound. As a programmer, you read and write a few bytes at a time and decide what they mean.
This tutorial covers the MIDI 1.0 basics in the order you will meet them: the signal chain, note numbers, channels and velocity, the bytes of a note, and a first program that reads and sends messages. At the end there is a path through the rest of the site.
The signal chain
- Controller. A keyboard, pad, sequencer or your program produces messages.
- Transport. The bytes travel over a 5-pin DIN cable, USB, Bluetooth LE, a network session or a virtual port inside one computer. The bytes are the same whichever way they travel.
- Receiver. A hardware synth, a DAW track, a software instrument or your program acts on each message as it arrives.
- Sound. Only the receiver makes audio, which goes to its own audio output. The same messages can sound like a piano on one synth and a drum kit on another.
A Standard MIDI File (.mid) stores the same messages with timing information so that a player can send them later. When a MIDI setup is silent, the fault is in one of these four links. The troubleshooting guide walks through each link in turn.
Note numbers, channels and velocity
Note numbers run from 0 to 127, one per semitone. 60 is middle C, 69 is the A above it (440 Hz in standard tuning), and adding 12 moves up one octave. The frequency of note n in equal temperament is 440 × 2^((n − 69) / 12).
| Note number | Hex | Name (MIDI 60 = C4) | Frequency |
|---|---|---|---|
| 21 | 15 | A0, lowest piano key | 27.5 Hz |
| 36 | 24 | C2 | 65.41 Hz |
| 48 | 30 | C3 | 130.81 Hz |
| 60 | 3C | C4, middle C | 261.63 Hz |
| 69 | 45 | A4 | 440 Hz |
| 72 | 48 | C5 | 523.25 Hz |
| 108 | 6C | C8, highest piano key | 4186.01 Hz |
Software does not agree on octave labels. Some products call note 60 “C3” rather than “C4”. The number is what travels on the wire, so log numbers rather than names when you debug. The MIDI note calculator converts any number to a name and frequency, and plays it.
Channels let one cable carry 16 independent parts. A receiver can play piano on channel 1 and bass on channel 2. On the wire, channels are numbered 0–15. Devices and DAWs display them as 1–16. In General MIDI, channel 10 (9 on the wire) is reserved for drums, and each note number selects a drum sound rather than a pitch.
Velocity (1–127) is how hard the key was struck. Most instruments map it to loudness, brightness or both. A Note On with velocity 0 means the same as Note Off. Many devices send it that way, so your code must accept both forms.
The three bytes of a note
Pressing and releasing middle C on channel 1 produces two messages:
90 3C 64 press: Note On, channel 1, note 60, velocity 100
80 3C 00 release: Note Off, channel 1, note 60, velocity 0
| Byte | Binary | Meaning |
|---|---|---|
90 | 1001 0000 | Status byte (high bit set). High nibble 9 = Note On. Low nibble 0 = channel 1. |
3C | 0011 1100 | Data byte (high bit clear): note number 60. |
64 | 0110 0100 | Data byte: velocity 100. |
Every MIDI 1.0 message works this way. A status byte (128–255) says what the message is, and zero, one or two data bytes (0–127) follow it. Change the low nibble to change the channel: 91 3C 64 is the same note on channel 2. The MIDI messages guide lists every message type, including Control Change, Program Change and Pitch Bend.
Your first program
The quickest way to talk to real MIDI devices is the Web MIDI API, which is built into Chromium-based browsers and desktop Firefox. You need no install and no compiler. The program below prints every note played on any connected input. It then plays C, E and G (an arpeggio) on the first output, with each note scheduled by timestamp rather than by timers.
export async function firstMidiProgram(log = console.log, nav = globalThis.navigator) {
const access = await nav.requestMIDIAccess(); // the browser asks the user first
// 1. Read: print every Note On / Note Off from every connected input.
for (const input of access.inputs.values()) {
input.onmidimessage = (event) => {
const [status, note, velocity] = event.data;
const type = status >> 4; // high nibble: 9 = Note On, 8 = Note Off
const channel = (status & 0x0f) + 1; // low nibble: 0–15, shown as 1–16
if (type === 0x9 && velocity > 0) log(`Note On ch ${channel} note ${note} velocity ${velocity}`);
else if (type === 0x8 || type === 0x9) log(`Note Off ch ${channel} note ${note}`);
};
}
// 2. Send: C4, E4, G4 on channel 1, one every 400 ms, each held for 350 ms.
const output = access.outputs.values().next().value;
if (!output) return log('No MIDI output found. Connect a synth or start a virtual port.');
const now = performance.now();
[60, 64, 67].forEach((note, i) => {
output.send([0x90, note, 100], now + i * 400); // Note On, channel 1, velocity 100
output.send([0x80, note, 0], now + i * 400 + 350); // Note Off for the same channel and note
});
log(`Sent 6 messages to ${output.name}`);
}
To run it, save it as a module, import it from a page served over HTTPS or from http://localhost, and call firstMidiProgram() from a button’s click handler. The browser will ask for permission to use MIDI devices. Without a hardware synth, you need something that makes sound from MIDI:
- macOS: enable the IAC Driver in Audio MIDI Setup and route it to a software instrument.
- Linux: a software synthesizer such as FluidSynth exposes an ALSA MIDI input with General MIDI sounds.
- Windows: use a hardware synth, a DAW with a virtual MIDI port, or a virtual-port utility.
If you want to see messages before writing code, connect a controller and use the live MIDI monitor. It decodes every byte as it arrives.
From live messages to files
Live receivers act when a message arrives or at its timestamp. A file needs its own timing: each event in a Standard MIDI File carries a delta time in ticks since the previous event, and a tempo event says how long a tick lasts. Build a pattern in the step sequencer and download it, then read the Standard MIDI File guide to see where every byte goes. The MIDI file analyzer shows the same structure for any file you drop on it.
Mistakes everyone makes once
- Off-by-one channels. Wire channel 0 is “channel 1” in every user interface. Convert at the boundary and nowhere else.
- Stuck notes. Every Note On needs a matching Note Off on the same channel and note number. If your program can stop mid-phrase, send the Note Offs (or a “panic”) on the way out.
- Ignoring velocity 0. Treat
9n kk 00as a Note Off, or notes will never end. - Timer-driven rhythm.
setTimeoutwanders by milliseconds. Schedule with timestamps instead. See audio timing in JavaScript.
Where to go next
- MIDI messages in bytes: every channel and system message, running status and a parser.
- Web MIDI API guide: permissions, hot-plugging, timestamps and error handling.
- Standard MIDI File format: chunks, delta times, meta events and a small reader and writer.
- Music data structures: ticks, tempo maps and note pairing for sequencers.
- Web Audio scheduling: playing sound on time in the browser.
- MusicXML basics and choosing an SDK when your project grows.
Tools to keep open while you learn: the note calculator, the MIDI CC chart, the MIDI player and the downloadable MIDI test files.