Morse Code Meets Web Audio: Building a Beep Generator in JavaScript

Morse Code Meets Web Audio: Building a Beep Generator in JavaScript

https://ift.tt/oUEW5sr

Although Morse code is nearly two centuries old, it’s a surprisingly fun way to explore the Web Audio API. Converting dots and dashes into sound takes only a small setup: an oscillator, a gain node, and a simple timing loop.

Understanding Morse timing

Morse code uses units of time. A dot lasts one unit, a dash lasts three, the gap between symbols in a letter is one unit, the gap between letters is three units, and the gap between words is seven. With an 80-millisecond unit, for example, a dash lasts 240 ms and a word gap lasts 560 ms. The rest is a matter of scheduling.

Creating the beeps

The Web Audio API generates tones without requiring audio files. Create an AudioContext, connect an oscillator to a gain node, and start and stop the oscillator to produce each dot and dash:

const ctx = new AudioContext();
const MORSE = { A: ".-", B: "-...", S: "...", O: "---" };

function beep(durationMs, when) {
  const osc = ctx.createOscillator();
  const gain = ctx.createGain();
  osc.type = "sine";
  osc.frequency.value = 700; // a pleasant 700 Hz tone
  osc.connect(gain).connect(ctx.destination);
  gain.gain.setValueAtTime(0.0001, when);
  gain.gain.exponentialRampToValueAtTime(0.5, when + 0.01);
  gain.gain.setValueAtTime(0.5, when + durationMs / 1000 - 0.01);
  gain.gain.exponentialRampToValueAtTime(0.0001, when + durationMs / 1000);
  osc.start(when);
  osc.stop(when + durationMs / 1000);
}

function playMorse(text) {
  const unit = 0.08; // 80 ms per unit
  let t = ctx.currentTime + 0.1;
  for (const ch of text.toUpperCase()) {
    if (ch === " ") { t += unit * 7; continue; }
    const code = MORSE[ch];
    if (!code) continue;
    for (const sym of code) {
      const len = sym === "." ? unit : unit * 3;
      beep(len * 1000, t);
      t += len + unit;
    }
    t += unit * 2; // letter gap (1 unit already added above)
  }
}

playMorse("SOS");

The gain envelope is important. Starting and stopping an oscillator abruptly can create an audible click, so gradually raising and lowering the gain over a few milliseconds makes each beep smoother.

Test it in your browser

Want to hear Morse code without writing any code? Morse Zone is a free online translator that converts text into Morse code and plays it in your browser. It’s a useful way to check that your own beep generator produces the correct patterns, and no signup is needed.

Ideas for what to build next

After your basic beeper is working, try adding a decoder that listens through the microphone, a speed control measured in words per minute, or a visual lamp that flashes in sync with the audio. Combining a classic communication system with a modern API makes for a great weekend project.

HI-FI News

via DEV Community: javascript https://ift.tt/dWL3let

October 22, 2026 at 06:39AM