Build a Real-Time Morse Code Decoder in the Browser with the Web Audio API
You can decode Morse code from a live microphone, in the browser, with no server and no libraries. Point your laptop mic at a practice oscillator — or tap a key next to your phone — and watch letters appear on screen as the sound arrives. It is a surprisingly small amount of code, and it teaches you three things every developer should understand: how to read audio in real time, how to turn a noisy analogue signal into clean digital decisions, and how timing itself can be the protocol.
This is different from decoding a recording. A recording lets you look ahead, normalise the whole file, and pick the perfect threshold. Live audio gives you none of that. You get a stream of samples, a noise floor that drifts, and a human on the other end whose timing is imperfect. Building for those constraints is the interesting part.
The pipeline in five steps
Live decoding is a pipeline:
- Capture — get microphone audio into an
AudioContext. - Measure — sample the signal level many times per second with an
AnalyserNode. - Decide — turn the level into a binary on/off stream with an adaptive threshold.
- Classify — measure how long each on/off run lasts, and call it a dot, a dash, a gap, or a word space.
- Decode — map dot/dash sequences to letters with a lookup table.
Each step is short. The whole decoder is under 150 lines.
Step 1: capture the microphone
The Web Audio API needs a user gesture before it will start, so wire the setup to a button click. getUserMedia gives you a media stream; createMediaStreamSource connects it to the audio graph.
let audioCtx, analyser, dataArray; async function startListening() { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); audioCtx = new (window.AudioContext || window.webkitAudioContext)(); const source = audioCtx.createMediaStreamSource(stream); analyser = audioCtx.createAnalyser(); analyser.fftSize = 2048; source.connect(analyser); dataArray = new Uint8Array(analyser.fftSize); requestAnimationFrame(sampleLoop); } Two details matter here. First, browsers block audio contexts until a user gesture — that is why this lives behind a button, not on page load. Second, fftSize of 2048 gives you a time-domain buffer of 2048 samples, about 43 milliseconds at 48 kHz. That is fine for our purposes: a dot at 20 words per minute lasts 60 milliseconds, so a 43 ms window still resolves it.
Step 2: measure the signal level
Every animation frame, read the time-domain data and compute a simple volume level — the root mean square of the samples. RMS is better than peak level here because a single click or pop will not fool it.
function currentLevel() { analyser.getByteTimeDomainData(dataArray); let sum = 0; for (let i = 0; i < dataArray.length; i++) { const v = (dataArray[i] - 128) / 128; sum += v * v; } return Math.sqrt(sum / dataArray.length); } requestAnimationFrame fires roughly 60 times a second, so you get a fresh level reading every ~16 ms. That is your sampling rate for the whole decoder, and it sets your timing resolution: you cannot distinguish events shorter than about 16 ms, but nothing in Morse code is that short.
Step 3: decide on or off with an adaptive threshold
The naive approach is a fixed threshold: level above 0.05 means "signal on". It works in a quiet room and fails everywhere else. A laptop fan, a passing car, or a different microphone will shift your noise floor and break the fixed value.
The fix is an adaptive threshold that learns the room. Track two running averages — one for the quiet floor, one for the signal peaks — and put the threshold between them.
let noiseFloor = 0.01; let signalPeak = 0.1; let isOn = false; function updateThreshold(level) { if (level > signalPeak) signalPeak = level; else signalPeak = signalPeak * 0.999 + level * 0.001; if (level < noiseFloor) noiseFloor = level; else noiseFloor = noiseFloor * 0.999 + level * 0.001; return (noiseFloor + signalPeak) / 2; } The slow decay (0.999) lets the estimates drift with the room while reacting quickly to real changes. The threshold sits halfway between floor and peak, so it adapts whether you are in a silent study or a noisy workshop. This single idea — never trust a fixed threshold on live audio — is the difference between a demo and a tool.
One more guard: add a little hysteresis. Require the level to cross the threshold by a small margin before flipping state, so a signal hovering near the line does not chatter on and off. A margin of 10–15% of the gap between floor and peak is enough.
Step 4: classify durations with a state machine
Now you have a binary stream: on, off, on, off. Record the timestamp of every transition, and the duration of each run tells you what it was. The classic ITU timing rules give you the reference values:
- Dot: 1 unit
- Dash: 3 units
- Gap inside a letter: 1 unit
- Gap between letters: 3 units
- Gap between words: 7 units
You do not know the sender's unit length in advance, so estimate it from the data. The shortest on-run you have seen recently is a good estimate of one unit — dots are the most common element, and they are the shortest.
let unit = 60; // milliseconds, initial guess (20 WPM) let onStart = 0, offStart = 0; let currentSymbol = ''; function onSignalStart(now) { onStart = now; } function onSignalEnd(now) { const dur = now - onStart; if (dur < unit * 1.5) { currentSymbol += '.'; unit = Math.min(unit, dur); } else currentSymbol += '-'; } function onSilenceEnd(now) { const dur = now - offStart; if (dur > unit * 5) { flushLetter(); flushWord(); } else if (dur > unit * 2) { flushLetter(); } } The classification boundaries sit between the expected values: anything under 1.5 units is a dot, anything over is a dash; a silence over 2 units ends a letter, over 5 units ends a word. Those midpoints are forgiving of human timing, which is never exact. A beginner sending at 10 WPM with wobbly spacing will still decode, because the ratios — not the absolute times — carry the information.
Note the unit estimate updates itself: every time a dot arrives shorter than the current estimate, the estimate tightens. Within a few characters the decoder has locked onto the sender's speed, whether they are crawling at 5 WPM or rattling along at 25.
Step 5: decode with a lookup table
The last step is the easy one — a dictionary from dot/dash strings to characters. The full table is 36 entries plus punctuation; here is the core of it.
const MORSE = { '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '-----': '0', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9' }; function flushLetter() { if (!currentSymbol) return; output += MORSE[currentSymbol] || '�'; currentSymbol = ''; } Unknown sequences get a replacement character rather than crashing the decoder — another small lesson in graceful degradation. In live decoding, an unrecognised pattern means the timing was off, not that the universe is broken, and the right response is to mark it and carry on.
Putting it together: the sample loop
The loop that ties it all together runs on every animation frame:
let lastState = false, lastChange = performance.now(); function sampleLoop() { const level = currentLevel(); const threshold = updateThreshold(level); const now = performance.now(); const state = level > threshold * 1.1; // hysteresis margin if (state !== lastState) { if (state) { onSignalStart(now); onSilenceEnd(now); } else { onSignalEnd(now); offStart = now; } lastState = state; } requestAnimationFrame(sampleLoop); } That is the whole decoder. Capture, measure, decide, classify, decode — five steps, no dependencies, no server, and it runs on any modern browser.
What goes wrong in practice
Three problems show up the moment you test with real humans and real rooms.
Background noise with a rhythm. A fan or a ticking clock can produce a regular on/off pattern that the decoder reads as dots. The adaptive threshold helps, but the real fix is frequency filtering: Morse practice tones are usually a single sine frequency (600–800 Hz). A BiquadFilterNode set to bandpass at the expected tone, inserted between the source and the analyser, removes most of the room before the level is even measured.
The first character is always wrong. The unit estimate starts as a guess, so the first few elements are classified against the wrong scale. Accept it: show the output with a short delay, or seed the unit length from a "calibrate" step where the user sends a few dots first. Professional decoders do exactly this.
Autoplay and permissions. Browsers require a user gesture for both microphone access and audio contexts, and some browsers suspend the context when the tab loses focus. Handle the resume() call on visibility change, and always tell the user why the browser is asking for microphone permission — a one-line explanation next to the button doubles the acceptance rate.
Why this is worth building
A live decoder is a better way to learn Morse code than any chart. When you hear a letter and watch it appear, the sound and the symbol fuse in a way reading never achieves. And the engineering transfers: adaptive thresholds, state machines over noisy streams, and timing-as-protocol show up in everything from voice activity detection to IoT sensor parsing. Morse code is 180 years old and still a good teacher.
If you want to practise hearing the code before you build the decoder — or check your timing against a reference — a free online Morse code translator lets you type text, hear it at a speed you choose, and see the dots and dashes as they play. Build the decoder, then use the translator to test it: send the audio from one tab into the microphone of another and watch your own code decode itself. That moment, when the machine reads what you sent, is the whole point.
Morse Zone runs a free Morse code translator with an alphabet chart and practice tools for learning the code by ear.
![Cargo UAV Autonomy and Flight AI — Ch.06: Route Planning and Airspace Integration [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F54s7rrr8fw0ipjpci49u.png)
![Cargo UAV Autonomy and Flight AI — Ch.05: Perception and Sensor Fusion for UAV [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faemm4fj7d911fwx0irut.png)
![Cargo UAV Autonomy and Flight AI — Ch.04: Autonomous Navigation for UAV [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F98idhn116ojz4pviet9j.png)
![Cargo UAV Autonomy and Flight AI — Ch.03: Flight Control Software [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fminle8x2lymdhmeo5fbt.png)
![Cargo UAV Autonomy and Flight AI — Ch.02: UAV System Architecture [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2w7u1ajhaoa23mrl0dqs.png)