Zero-Backend Speech Synthesis: Running Piper Voice Models with ONNX Runtime Web

Zero-Backend Speech Synthesis: Running Piper Voice Models with ONNX Runtime Web

Imagine a reading app for language learners. A user taps a sentence and expects to hear it spoken, immediately, every time, including on a train with one bar of signal. If the app calls a cloud text-to-speech endpoint, each tap becomes a network round trip: a request goes out, audio comes back, and playback starts only when enough of it has arrived. On a good connection that feels fine. On a bad one the voice stutters, the first word is late, and the whole feature stops working the moment the user goes offline. There is also a quieter cost. The text the user is reading, which may be private, leaves their device for every sentence.

Running the voice in the browser removes the round trip, the dependency on connectivity and the data transfer, at the price of shipping a model to the client and doing the computation on hardware you do not control. This article walks through how that works with Piper, a family of small neural voices, and ONNX Runtime Web, the engine that runs the exported models in a page. We cover what happens between text and sound, what the model expects as input, why phonemization is the awkward part, how to run inference without freezing the page, how to stream audio so it starts quickly, and when you should not do any of this on the client.

What happens between text and sound

A neural text-to-speech system is a pipeline, and each stage has its own failure modes. Piper's pipeline has five stages.

  1. Text normalization. Turn written text into something speakable. "3 PM", "Dr.", "2026-10-25" and "$4.50" are not pronounceable as written. Some voices handle part of this inside the phonemizer, but most of the work is yours.
  2. Phonemization. Convert the normalized text into a sequence of phonemes, the sound units of the language. This step is language-specific and, as we will see, the hardest to move into a browser.
  3. Phoneme-to-ID mapping. Each voice ships a table that maps phoneme symbols to integer IDs. The model never sees letters or phoneme symbols, only these integers.
  4. Model inference. The neural network takes the ID sequence and produces a waveform. Piper voices are built on VITS, an architecture that generates audio end to end, without a separate vocoder stage that you have to run afterwards. That is one reason the exported voices are compact and simple to deploy.
  5. Playback. The output is an array of floating-point samples at the voice's sample rate. Your code turns it into something the browser's audio system can schedule.

This view is useful because it tells you where problems come from. A voice that mispronounces a word usually failed at stage one or two. A crash with an obscure tensor error is stage three or four. Audio that sounds like a chipmunk or a slowed-down tape is stage five, specifically a sample rate mismatch. Debug by stage, not by "the TTS is broken".

Why Piper suits the browser

Several properties make Piper models good candidates for client-side use, and each one is a property of the design rather than a marketing claim.

  • They are exported as ONNX files. ONNX is a portable model format with a runtime that targets many environments. ONNX Runtime Web is the build of that runtime for browsers, with a WebAssembly backend and, in recent versions, a WebGPU backend. You are running the same graph the exporter produced, not a re-implementation.
  • They are small relative to general-purpose models. Voices come in quality tiers, from very low to high. Lower tiers use a lower sample rate (commonly 16 kHz) and a smaller network. Medium and high tiers commonly use 22.05 kHz. File sizes range from tens of megabytes to roughly a hundred or more for the largest, so check the voice you intend to ship rather than assuming.
  • Each voice ships with a JSON config. The config states the sample rate, the phoneme-to-ID map, the number of speakers and default inference parameters. This is the contract between the voice and your code, and reading it instead of hard-coding values is what lets you swap voices without changing the player.
  • Inference is deterministic in shape. The input is a bounded sequence of IDs and the output is a bounded array of samples, so there is no token-by-token generation loop to manage and no growing context.
  • There are voices for many languages, including Vietnamese. Quality and licensing vary by voice, so treat the voice catalogue and each voice's model card as the source of truth.
Check the licence before you ship. The software and each individual voice can carry different licences, and the upstream project's status and licensing have changed over time. Read the current repository and the model card for the exact voice you plan to bundle, including any restrictions that come from the dataset the voice was trained on.

The model contract: config, tensors and a minimal pipeline

Piper voices export with a small set of inputs: the phoneme ID sequence, its length, a three-element array of scales controlling the sound, and optionally a speaker ID for multi-speaker voices. The output is a single waveform tensor. Input and output names come from the exported graph, so inspect session.inputNames and session.outputNames once for your voice and do not trust any snippet, including this one, to match exactly.

The three scales are noise scale, length scale and noise width. Length scale is the one people reach for first: values above 1.0 slow the speech down and below 1.0 speed it up. Noise scale and noise width add variation to the generated audio and to the phoneme durations. The config's inference section carries sensible defaults, so start there and change one value at a time.

import * as ort from 'onnxruntime-web';

export async function loadVoice(modelUrl, configUrl) {
  const config = await (await fetch(configUrl)).json();
  const session = await ort.InferenceSession.create(modelUrl, {
    executionProviders: ['wasm'],
    graphOptimizationLevel: 'all',
  });
  return { session, config };
}

// Piper interleaves a pad id between phonemes and brackets the sequence
// with begin/end markers. Confirm the exact layout against the reference
// implementation for your voice.
export function toIds(phonemes, idMap) {
  const ids = [...idMap['^']];
  for (const p of phonemes) {
    const mapped = idMap[p];
    if (!mapped) { console.warn('unmapped phoneme', p); continue; }
    ids.push(...mapped, ...idMap['_']);
  }
  ids.push(...idMap['$']);
  return ids;
}

export async function synthesize({ session, config }, ids, speakerId = 0) {
  const n = ids.length;
  const inf = config.inference ?? {};
  const feeds = {
    input: new ort.Tensor('int64', BigInt64Array.from(ids, (v) => BigInt(v)), [1, n]),
    input_lengths: new ort.Tensor('int64', BigInt64Array.from([BigInt(n)]), [1]),
    scales: new ort.Tensor('float32', Float32Array.from([
      inf.noise_scale ?? 0.667,
      inf.length_scale ?? 1.0,
      inf.noise_w ?? 0.8,
    ]), [3]),
  };
  if ((config.num_speakers ?? 1) > 1) {
    feeds.sid = new ort.Tensor('int64', BigInt64Array.from([BigInt(speakerId)]), [1]);
  }
  const out = await session.run(feeds);
  return out.output.data; // Float32Array, mono PCM at config.audio.sample_rate
}

// Schedule a chunk to start exactly when the previous one ends.
export function playChunk(ctx, samples, sampleRate, startAt) {
  const buffer = ctx.createBuffer(1, samples.length, sampleRate);
  buffer.copyToChannel(samples, 0);
  const node = ctx.createBufferSource();
  node.buffer = buffer;
  node.connect(ctx.destination);
  const when = Math.max(startAt, ctx.currentTime);
  node.start(when);
  return when + buffer.duration;
}

Two details in that code cause most first-day bugs. The IDs must be 64-bit integers, which in JavaScript means BigInt64Array, and mixing ordinary numbers into it throws. And the playback buffer must be created with the voice's own sample rate, taken from config.audio.sample_rate. Hard-coding 22050 and then loading a 16 kHz voice produces audio that plays too fast and too high.

Phonemization is the hard part in the browser

Everything above is mechanical. Phonemization is where the real work is, because the model was trained on phoneme sequences produced by a specific tool and expects the same tool's output at runtime. Piper's training data was phonemized with eSpeak-NG for most languages, so the closest match is to run the same engine. In a browser that means eSpeak-NG compiled to WebAssembly, which adds its own payload and a data file of language rules, and has its own licence terms to review.

There are three honest options.

  • Phonemize in the page with a WebAssembly build of the same engine. Highest fidelity to what the voice was trained on. Cost: extra download, extra initialization, and another component to keep working across browsers.
  • Phonemize on the server and ship only the phoneme IDs. The model still runs on the device and the heavy synthesis stays private to the client, but the text must reach your server, which partly undoes the privacy and offline benefits.
  • Write a rule-based converter for one language. Reasonable for a language with regular spelling and a small vocabulary, such as a controlled set of phrases. It is not reasonable for open-ended English text.

Vietnamese deserves a specific warning. It is a tonal language, and tone is carried in the diacritics. A pipeline that strips or mangles Unicode normalization turns different words into the same string. Normalize text to a single Unicode form (NFC is the usual choice) before phonemization, and test with minimal pairs that differ only in tone. Written numbers, dates, currency and abbreviations also need a normalization step that expands them into words in the right language. The model will not do this for you, and an unexpanded "2026" is read in whatever way the phonemizer guesses.

Running inference on ONNX Runtime Web without freezing the page

Synthesis is compute-heavy and the main thread is where your interface lives. Run the session in a Web Worker and exchange messages: the page posts text or phoneme IDs, the worker posts back sample arrays, ideally as transferable buffers so no copy is made. Create the session once and reuse it, because loading and initializing a model is far more expensive than a single run.

The execution provider you choose changes behavior more than any tuning flag. The table below compares them by property, not by invented speed numbers; measure on the devices your users actually own.

Backend Where it runs Availability Strength Watch out for
WebAssembly (CPU) CPU, optionally multi-threaded with SIMD Essentially every modern browser Predictable, widest compatibility Multi-threading needs cross-origin isolation headers; otherwise it runs single-threaded
WebGPU GPU Growing, but not universal, and varies by platform Can be faster for large graphs Operator coverage differs; unsupported ops may fall back or fail. For small models it may not beat the CPU path
Server-side inference Your hardware Anywhere with a network Consistent speed regardless of device Requires connectivity, sends text off the device, and costs you compute

For a model of this size, start with the WebAssembly backend. It works everywhere, and a small VITS-style network is unlikely to be limited by the arithmetic in a way a GPU rescues. Try WebGPU as an experiment, with a fallback list such as ['webgpu', 'wasm'], and keep it only if it measures better on your target devices.

To get multi-threaded WebAssembly, the page must be cross-origin isolated, which means serving it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. That in turn constrains every third-party resource the page loads, so decide early; retrofitting isolation into a page full of embedded widgets is painful.

Loading and caching the model

The model file is the biggest cost the user pays, so treat it as an installable asset. Download it once, store it with the Cache Storage API or in IndexedDB, show real progress, and verify it loads before reporting the feature as ready. Offer the voice as an explicit opt-in on metered connections. A service worker that serves the model and runtime files from cache is what makes the feature genuinely offline, because without it a cold start with no network fails even though the voice is "installed".

Streaming and playback: getting the first sound out quickly

Time to first audio is what the user perceives. It is determined by the length of the first thing you synthesize, not by the total length of the text. Synthesizing a long paragraph as one request makes the user wait for all of it. Instead, split the text into sentences or clauses, synthesize the first one immediately, start playback, and synthesize the rest while the first plays.

  1. Split on sentence boundaries, and keep the first chunk short enough to finish quickly.
  2. Run chunks through the worker one at a time, in order.
  3. Schedule each result with playChunk, passing the end time of the previous chunk so playback is gapless.
  4. If synthesis stays ahead of playback, the user hears continuous speech. If a chunk is slow, the queue drains and there is an audible pause, which tells you the chunk is too long or the device too slow.
  5. To cancel, stop the scheduled sources and clear the queue. A worker that is already mid-inference cannot be interrupted partway, so discard its result when it returns.

Browsers block audio until the user interacts with the page. Create or resume the AudioContext inside a click or tap handler. Apps that "work on desktop but are silent on the phone" are usually violating this rule.

Failure modes

  • Chipmunk or slow-motion audio. The buffer sample rate does not match the voice. Read it from the config.
  • Garbled or clipped speech. A wrong or incomplete phoneme map, text the phonemizer was not designed for, or IDs assembled in the wrong layout. Log unmapped phonemes rather than skipping them silently.
  • Memory pressure on phones. Large models and long inputs can exhaust memory on low-end devices, and the failure may look like a page reload. Bound the chunk length, reuse one session, and offer a smaller voice tier on constrained devices.
  • Silent failure under a strict Content Security Policy. WebAssembly compilation and worker creation can be blocked by policy. Check the browser console for CSP violations when the runtime fails to initialize.
  • Model loads on desktop and fails on a phone. Hitting storage quotas, memory ceilings or a missing backend feature. Test on at least one older mid-range phone before calling the feature done.
  • Click or pop between chunks. Chunks that begin or end on a non-zero sample. A very short fade at chunk boundaries masks it.
  • Stale model after an update. A cached voice that no longer matches a new config. Version the model and config together and invalidate them as a pair.

When not to synthesize on the client

  • You need the best naturalness available. Small on-device voices are good for their size and clearly below the best large cloud voices for expressive, long-form narration. Listen to your actual content before deciding.
  • You need many voices, voice cloning or fine-grained emotional control. The client path is a fixed set of downloaded voices.
  • Your audience is on low-end hardware or metered data and the voice file is a heavy first-run cost for a feature few use.
  • The text is long and generated all at once, such as an hour of audio. Server hardware will do it faster and you do not need to keep a laptop busy.
  • You cannot satisfy the licence terms of the voice or the phonemizer for your distribution model.

Decision checklist, common mistakes and what to do on Monday

Work through these before you commit.

  1. Is offline use or text privacy a real requirement? If neither, a hosted voice may be simpler.
  2. Which languages do you need, and does a voice of acceptable quality exist for each? Listen to samples with your own text.
  3. How will you phonemize each language in the page, and have you read that component's licence?
  4. What is the model download size on the slowest connection you support, and when does the user consent to it?
  5. Does your page tolerate cross-origin isolation if you want threading?
  6. What does the user hear when synthesis fails? Define the fallback.

Mistakes that appear repeatedly:

  • Synthesizing whole documents at once and then wondering why the first word is slow.
  • Hard-coding sample rate, speaker count or scales instead of reading the voice config.
  • Running inference on the main thread and blaming the model for a frozen interface.
  • Creating a new inference session for every sentence.
  • Skipping text normalization and treating mispronounced numbers as a model defect.
  • Testing only on a developer laptop.

A practical first week looks like this. On day one, load one voice and one hard-coded sentence in a plain page, and confirm you can hear it at the right pitch. On day two, move inference into a worker and reuse the session. On day three, add sentence chunking and gapless scheduling. On day four, replace the hard-coded phonemes with a real phonemizer for your language and build a small list of tricky sentences, including numbers and tone-sensitive Vietnamese pairs, as a regression set. On day five, test on a mid-range phone with the network off, and write down what the user experiences. Only then decide whether the quality and the download size are acceptable for your product.