DEV Community

Cover image for How I Built a 100% Client-Side Robot Voice Generator & 1982 SAM Synth with Web Audio API (Zero Server Cost)
汪福杰
汪福杰

Posted on

How I Built a 100% Client-Side Robot Voice Generator & 1982 SAM Synth with Web Audio API (Zero Server Cost)

Most online voice tools follow the same architecture: send text or audio to a backend API, run inference on a GPU server, stream back an MP3, and put a sign-up wall or credit meter in front of downloads to cover the compute bill.

For photorealistic neural voices, that backend is unavoidable. But for stylized robotic speech, retro 1982 computer voices, and 8-bit audio distortion—the kind indie game developers, YouTubers, and synth hobbyists actually reach for—modern browsers already ship a fast DSP engine out of the box: the Web Audio API.

This week I shipped Robot Voice Maker, a zero-backend audio studio where every speech render, microphone recording, file decode, DSP filter pass, and WAV/MP3 export runs 100% locally in the visitor's browser.

Here is the architecture, the key DSP code, the open-source preset pack I extracted from it, and an honest breakdown of where this client-side approach beats existing tools—and where it falls short.


1. The Zero-Backend Signal Chain

Everything runs inside AudioContext (live playback + oscilloscope visualization) and OfflineAudioContext (deterministic, faster-than-real-time rendering for downloads):

[Text Input] ──► meSpeak (en-us / en-rp) OR sam-js (1982 Formant Synth)
                        │
[Mic / MP3 / MP4] ──────┴──► AudioBuffer (Decoded Locally in RAM)
                                   │
                                   ▼
                 ┌───────────────────────────────────┐
                 │   OfflineAudioContext DSP Chain   │
                 │  1. Sine Ring Modulation (Hz/Mix) │
                 │  2. Short Comb Delay Resonance    │
                 │  3. Bit-Depth & Sample-Rate Hold  │
                 │  4. Radio Band-Pass (420–3200 Hz) │
                 │  5. Subtle Slapback Room Echo     │
                 └───────────────────────────────────┘
                                   │
                 ┌─────────────────┴─────────────────┐
                 ▼                                   ▼
      Canvas Oscilloscope                 Local Blob Downloads
     (Real-time AnalyserNode)          16-bit PCM WAV / 128k MP3
Enter fullscreen mode Exit fullscreen mode

Because zero bytes of audio or text ever leave the browser (anyone can verify it in the DevTools Network tab), server compute stays at $0/month, and there is no need for accounts, watermarks, or daily render caps.


2. Core DSP Implementation in Plain JavaScript

A. Ring Modulation + Sample-and-Hold Bitcrusher

A surprising mistake in many browser robot voice tools is applying heavy ring modulation at 100% wet mix, which destroys intelligibility. Keeping a dry/wet Metallic Mix (0%–45%) around 44–92 Hz gives clean speech a metallic sci-fi sheen while staying easy to understand.

For retro game and lo-fi microphone effects—which I also broke out into a standalone online bitcrusher with A/B bypass—two tiny loops handle both bit-depth quantization and sample-rate decimation:

export function applyRingModulation(input, sampleRate, { ringMixPercent = 0, ringHz = 68 }) {
  const mix = Math.max(0, Math.min(1, ringMixPercent / 100));
  if (mix === 0) return new Float32Array(input);

  const out = new Float32Array(input.length);
  const twoPiF = 2 * Math.PI * ringHz;
  for (let i = 0; i < input.length; i++) {
    const carrier = Math.sin((twoPiF * i) / sampleRate);
    out[i] = input[i] * (1 - mix) + input[i] * carrier * mix;
  }
  return out;
}

export function applyBitcrusher(input, sourceSr, { bitDepth = 4, sampleRateHz = 8000, mixPercent = 100 }) {
  const bits = Math.max(1, Math.min(16, bitDepth));
  const targetSr = Math.max(1000, Math.min(sourceSr, sampleRateHz));
  const wet = Math.max(0, Math.min(1, mixPercent / 100));

  const out = new Float32Array(input.length);
  const step = bits >= 16 ? 0 : Math.pow(0.5, bits - 1);
  const holdSamples = Math.max(1, Math.round(sourceSr / targetSr));

  let held = 0;
  for (let i = 0; i < input.length; i++) {
    if (i % holdSamples === 0) {
      let s = input[i];
      if (step > 0) s = Math.round(s / step) * step;
      held = Math.max(-1, Math.min(1, s));
    }
    out[i] = input[i] * (1 - wet) + held * wet;
  }
  return out;
}
Enter fullscreen mode Exit fullscreen mode

Passing that quantized buffer through an OfflineAudioContext BiquadFilterNode (lowpass at 3.4 kHz–8.5 kHz for vintage handheld/headset roll-off, or a 420 Hz–3.2 kHz band-pass for station intercoms) tames harsh aliasing spikes before export.

B. Bringing Back the 1982 SAM Formant Synthesizer

Classic 1980s robot voices weren't filtered recordings—they were pure formant synthesis. Using sam-js (a JavaScript port of 1982's Software Automatic Mouth), you get raw 8-bit unsigned PCM at 22,050 Hz driven by four integer registers (speed, pitch, throat, mouth) plus Sing (monotone) and Phonetic modes:

// Convert sam-js 8-bit unsigned PCM [0..255] into a Web Audio AudioBuffer
function renderSamToBuffer(audioCtx, text, { speed = 72, pitch = 64, throat = 128, mouth = 128, sing = false, phonetic = false }) {
  const sam = new window.SamJs({ speed, pitch, throat, mouth, singmode: sing, phonetic });
  const rawU8 = sam.buf8(text);
  const buffer = audioCtx.createBuffer(1, rawU8.length, 22050);
  const ch = buffer.getChannelData(0);
  for (let i = 0; i < rawU8.length; i++) {
    ch[i] = (rawU8[i] - 128) / 128;
  }
  return buffer;
}
Enter fullscreen mode Exit fullscreen mode

Because sam-js has its own quirky parameter space (lower speed speaks faster, lower pitch sounds higher) and supports direct ARPABET-like phoneme editing, I gave it a dedicated workspace as a 1982 SAM voice generator with all 6 original 1982 manual character presets (Elf, Little Robot, Stuffy Guy, Little Old Lady, Extra-Terrestrial, plus SAM Default).

C. Client-Side WAV & MP3 Export

Writing an uncompressed 16-bit PCM WAV header takes ~25 lines of DataView code and runs instantaneously. For MP3 export (often requested by YouTube and mobile editors), lamejs encodes 128 kbps mono MP3 blocks directly from Int16Array samples into a Blob—no FFmpeg WASM multi-megabyte payload required.


3. Open-Source DSP Presets (MIT License)

I extracted all 20 tuned presets across the three tools into an open-source JSON + Web Audio helper repo so other web and indie game developers can drop them straight into their own projects:

  • GitHub Repo: FujieW/robot-voice-dsp-presets (8 robot voice presets, 7 SAM 1982 formant presets, 5 vintage bitcrusher presets, and apply-dsp-preset.js)

If you want to audition the presets in-browser before grabbing the JSON:


4. Honest Comparison vs. Existing Voice Tools (Pros & Cons)

Before building this, I tested the most popular alternatives across four categories. No single architecture wins every use case—here is how client-side Web Audio stacks up honestly:

Dimension Client-Side Web Audio (Robot Voice Maker) Cloud Neural AI TTS (e.g., ElevenLabs, Murf) Classic Web Generators (e.g., LingoJam, Voicegenerator.io) Desktop Real-Time Apps (e.g., Voicemod, Clownfish)
Voice Realism Stylized / retro / crisp synthetic (non-neural) Best (human-like emotional AI voices) Basic robotic / browser TTS Good real-time human voice effects
Privacy & Uploads 100% local in browser (zero uploads) Audio/text sent to cloud servers Mixed (some upload files to backend) Local desktop processing
Sign-up & Pricing Free, no account, no watermark Account required; credit/subscription limits Mostly free, often ad-heavy or basic UI Installer required; pro voices paywalled
Export & DSP Control Instant WAV + MP3, fine DSP sliders, 1982 SAM, 8-bit crusher High-quality MP3/WAV (tiered by plan) Basic WAV or limited preset tweaks Best for live Discord/OBS mic routing
Commercial Rights Free personal & commercial (license) Paid tier usually required for commercial use Often unclear or unspecified Varies by license

Where Client-Side Web Audio Wins (Advantages)

  1. Zero friction & zero server cost: No login walls, no rate limits, no cloud inference latency, and private audio recordings never touch a third-party server.
  2. Deterministic retro & sci-fi character: For indie games, analog horror, chiptune tracks, and retro YouTube intros, neural AI often sounds too polished. Formant synthesis + ring modulation + bitcrushing nails the exact vintage aesthetic and stays 100% reproducible from JSON parameters.
  3. Works across desktop & mobile browsers: Nothing to install; even works offline once the page and voice dictionary are cached.

Real Trade-offs & Limitations (Disadvantages)

  1. Not photorealistic voice cloning: If you need a natural human narrator with subtle emotional inflection, cloud neural TTS platforms are still dramatically better.
  2. Cold-start voice dictionary download: The local clear-English synthesizer (meSpeak) fetches a ~1.2 MB JSON voice pack on the very first run, which adds 1–2 seconds of delay on slow mobile 4G (cached afterward).
  3. Batch / offline workflow, not live Discord routing: Browser security sandboxing prevents creating a virtual system microphone, so desktop apps like Voicemod remain the right choice for live streaming or live gaming voice chat.
  4. Browser memory ceiling on mobile: Decoding very large MP4/WAV files (>35 MB or >5 minutes on iOS Safari) can hit mobile tab RAM limits because OfflineAudioContext processes uncompressed Float32 PCM in memory.

5. Two Practical Lessons Learned Shipping Web Audio to Real Users

  1. Mobile Safari audio unlock & layout stability matter more than you think: Over 60% of my early visitors arrived on mobile browsers. Calling audioCtx.resume() synchronously inside the user's tap handler is mandatory on iOS Safari, and reserving fixed heights for dynamic status messages + switching Google Fonts to display=optional eliminated mobile Cumulative Layout Shift (CLS).
  2. Keep clean presets at 0% ring modulation by default: When users land on a robot voice tool, their first test is usually a clean AI assistant voice—not an unintelligible sci-fi screech. Separating clean presets (01–04) from heavy retro/mech DSP (05–08) noticeably improved repeat renders per session.

I'd love feedback from anyone working with Web Audio API, AudioWorklet, or browser-side DSP—especially if you have favorite formant recipes or bitcrusher chains to add to the open-source preset repo!

Top comments (0)