New AssemblyAI-TTS-1: Text-to-speech for voice agents. Learn more
Insights & Use Cases

JavaScript text to speech: speechSynthesis and the AssemblyAI TTS API (with React)

Use the browser's speechSynthesis API, then upgrade to natural voices with AssemblyAI-TTS-1 in Node, the browser and React. Code included.

Abstract green cylinder illustration

Written by

Stefan Rosanitsch

Published on

4 April 2022

speechSynthesis is the browser's built-in text-to-speech interface. It's part of the Web Speech API, it's available as window.speechSynthesis in every major browser, and it turns a string into spoken audio with one line of JavaScript and no API key. That makes it the fastest way to add a "read this aloud" button to a page.

It also has a ceiling. The voices come from the user's operating system, so your app sounds different on every device, and you can't save the audio, stream it to a phone call or control how it pronounces an order number.

This guide covers both sides. First, the browser's speechSynthesis API, done properly. Then the upgrade path: generating natural speech with the AssemblyAI Text-to-Speech API in Node, playing it in the browser without exposing your API key, and wrapping both engines in a React hook.

What is the Web Speech API?

The Web Speech API is a browser standard with two halves:

For text to speech you work with two objects. window.speechSynthesis is the controller: it speaks, pauses, resumes, cancels and lists voices. SpeechSynthesisUtterance is one piece of text plus how to say it: voice, language, rate, pitch and volume. The MDN reference for SpeechSynthesis documents every property.

Speak text with window.speechSynthesis

Start with a plain HTML page: a text box, a voice picker and two buttons.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JavaScript Text-to-Speech</title>
  </head>
  <body>
    <textarea id="text" rows="4" cols="50">Your order number is 4 8 1 5 2.</textarea>
    <select id="voice"></select>
    <label>Rate <input id="rate" type="range" min="0.5" max="2" step="0.1" value="1" /></label>
    <label>Pitch <input id="pitch" type="range" min="0" max="2" step="0.1" value="1" /></label>
    <button id="speak">Speak</button>
    <button id="stop">Stop</button>
    <script src="script.js"></script>
  </body>
</html>

Then the script. Three details trip people up, and the code handles all of them:

const synth = window.speechSynthesis;
const textEl = document.querySelector("#text");
const voiceEl = document.querySelector("#voice");

if (!("speechSynthesis" in window)) {
  alert("This browser doesn't support speechSynthesis.");
}

// 1. Voices load asynchronously. getVoices() is often empty on first call,
//    so fill the list again when the browser fires voiceschanged.
function loadVoices() {
  const voices = synth.getVoices();
  voiceEl.innerHTML = voices
    .map((v, i) => `<option value="${i}">${v.name} (${v.lang})</option>`)
    .join("");
}
loadVoices();
synth.addEventListener("voiceschanged", loadVoices);

document.querySelector("#speak").addEventListener("click", () => {
  // 2. speak() queues. Cancel first so a second click doesn't stack utterances.
  synth.cancel();

  const utterance = new SpeechSynthesisUtterance(textEl.value);
  utterance.voice = synth.getVoices()[voiceEl.value] ?? null;
  utterance.rate = Number(document.querySelector("#rate").value);
  utterance.pitch = Number(document.querySelector("#pitch").value);
  utterance.onend = () => console.log("Finished speaking");

  synth.speak(utterance);
});

document.querySelector("#stop").addEventListener("click", () => synth.cancel());

The third detail: browsers only allow speech after a user gesture, so call speak() from a click handler, not on page load.

That's a working text-to-speech app in about 30 lines. For accessibility features and prototypes, it may be all you need.

The limits of browser text to speech

speechSynthesis is free and instant, but it isn't built for products where the voice is part of the experience:

  • The voice changes with the device. The voices are the operating system's, so the same page sounds different on Chrome for Windows, Safari on iOS and Firefox on Linux. Some voices stream from the browser vendor's servers, others run locally, and the list differs between machines.
  • No audio file. The browser speaks straight to the speakers. You can't save an MP3, attach audio to an email, or send it down a phone line.
  • Browser only. There's no speechSynthesis in Node, so server-side jobs (narrating content, voice agents, IVR prompts) need something else.
  • Little control over the hard parts. Order numbers, email addresses and names are where TTS voices fail, and with the browser you can only accept what the OS voice does.

When you hit those limits, use a text-to-speech API. The rest of this guide uses AssemblyAI's.

Give your app one consistent, natural voice

AssemblyAI-TTS-1 sounds the same on every device, reads order numbers and codes correctly, and works from Node and the browser. Get a free API key to try it.

Sign up free

Generate speech with the AssemblyAI TTS API in Node

AssemblyAI's text-to-speech model, AssemblyAI-TTS-1 (assemblyai-tts-1), is trained on millions of hours of audio, including real conversational data. It has thousands of voices across English, Spanish, German, French, Italian and Portuguese. In the launch post's evals it scored 93.7% entity accuracy on a pronunciation set of names, numbers and codes, and 99.0% word accuracy. Production time to first audio is 90 ms. The launch post's 47 ms median time to first byte was measured in a single-client lab test, so treat it as a lab figure.

Install the AssemblyAI JavaScript SDK (version 4.42.0 or later includes client.tts):

npm install assemblyai

Then synthesize a WAV file. container: "wav" wraps the audio in a playable file; without it, you get raw 24 kHz, 16-bit PCM.

// synthesize.mjs
import { writeFileSync } from "node:fs";
import { AssemblyAI } from "assemblyai";

const client = new AssemblyAI({ apiKey: process.env.ASSEMBLYAI_API_KEY });

const response = await client.tts.synthesize({
  text: "Your order number is 4 8 1 5 2. It ships Thursday.",
  voice_id: "aai-kyla", // Kyla
  container: "wav",
});

writeFileSync("speech.wav", response.audio);
console.log(
  `${response.audioDurationMs} ms of audio, ${response.billedCharacters} characters billed`
);

Run it with ASSEMBLYAI_API_KEY=your_key node synthesize.mjs and open speech.wav. The complete code, with a React demo, is in the companion repo on GitHub.

A few options worth knowing:

  • voice_id takes a voice's ID from the voice catalog in the AssemblyAI dashboard (IDs never change), a library slug such as aai-kyla (the API's default English voice), or the slug of one of your cloned voices. Our guide to choosing a voice helps you pick one.
  • language takes the language's English name: "spanish", "german" and so on. The API doesn't detect language, so set it when the text isn't in the voice's own language.
  • encoding: "mp3" returns MP3 instead of PCM, if you're saving files for the web.
  • client.tts.stream() returns the audio as it's generated, as an async iterable, for long texts you want to start playing early.

Working in Python instead? The same API is covered in our Python text-to-speech tutorial.

Play AssemblyAI TTS in the browser without exposing your API key

Never put your AssemblyAI API key in front-end code. Anyone can read it from the page. Instead, mint a short-lived temporary token on your server and let the page use that. A token works wherever an API key does on the TTS HTTP API, and the API answers cross-origin requests, so the page can call it directly.

On the server, add a token route. This one uses Express:

// server.mjs
import express from "express";
import { AssemblyAI } from "assemblyai";

const client = new AssemblyAI({ apiKey: process.env.ASSEMBLYAI_API_KEY });
const app = express();
app.use(express.static("public"));

app.get("/tts-token", async (req, res) => {
  // A fresh, short-lived token per request. It can't mint other tokens.
  const token = await client.tts.createTemporaryToken({ expires_in_seconds: 60 });
  res.json({ token });
});

app.listen(3000, () => console.log("http://localhost:3000"));

In the page, fetch a token, request the speech as a WAV file, and play it with an ordinary Audio element:

// public/tts.js
const KYLA = "aai-kyla";

async function speakWithAssemblyAI(text, voiceId = KYLA) {
  const { token } = await (await fetch("/tts-token")).json();

  const res = await fetch("https://tts.us.assemblyai.com/v1/speech", {
    method: "POST",
    headers: { Authorization: token, "Content-Type": "application/json" },
    body: JSON.stringify({ text, voice_id: voiceId, container: "wav", stream: false }),
  });
  if (!res.ok) throw new Error(`TTS request failed: ${res.status}`);

  const url = URL.createObjectURL(await res.blob());
  const audio = new Audio(url);
  audio.onended = () => URL.revokeObjectURL(url);
  await audio.play();
}

document.querySelector("#speak").addEventListener("click", () => {
  speakWithAssemblyAI(document.querySelector("#text").value);
});

"stream": false asks for the whole file at once, which is what you want for a short WAV. Keep expires_in_seconds short and mint a new token for each request. The temporary token docs cover the EU token host and a streaming PCM player for longer texts.

For low-latency, interruptible speech (a voice assistant that talks back), use the SDK's WebSocket session in the browser instead. It takes the same token:

import { TextToSpeechSession } from "assemblyai";

const session = new TextToSpeechSession({ token, voiceId: KYLA });
await session.connect();
for await (const chunk of session.speak("Hi! How can I help?")) {
  playPcm(chunk); // raw 24 kHz 16-bit PCM; see the word boundaries section for a player
}
await session.close();

If you're building a full conversational app, our tutorial on building a voice assistant app puts streaming speech-to-text, an LLM and this TTS session together.

React text to speech with a useSpeech hook

In React, wrap both engines in one hook: the browser's speechSynthesis for free, instant playback, and the AssemblyAI API when you want a consistent, natural voice. The hook tracks whether something is speaking and cleans up when the component unmounts.

// useSpeech.js
import { useCallback, useEffect, useRef, useState } from "react";

const KYLA = "aai-kyla";

export function useSpeech() {
  const [speaking, setSpeaking] = useState(false);
  const audioRef = useRef(null);

  const stop = useCallback(() => {
    if ("speechSynthesis" in window) window.speechSynthesis.cancel();
    audioRef.current?.pause();
    setSpeaking(false);
  }, []);

  // Free, in-browser voice from the operating system
  const speakBrowser = useCallback((text, { voice = null, rate = 1, pitch = 1 } = {}) => {
    if (!("speechSynthesis" in window)) return;
    stop();
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.voice = voice;
    utterance.rate = rate;
    utterance.pitch = pitch;
    utterance.onstart = () => setSpeaking(true);
    utterance.onend = () => setSpeaking(false);
    utterance.onerror = () => setSpeaking(false);
    window.speechSynthesis.speak(utterance);
  }, [stop]);

  // AssemblyAI-TTS-1, using a temporary token from your server
  const speakAssemblyAI = useCallback(async (text, voiceId = KYLA) => {
    stop();
    const { token } = await (await fetch("/tts-token")).json();
    const res = await fetch("https://tts.us.assemblyai.com/v1/speech", {
      method: "POST",
      headers: { Authorization: token, "Content-Type": "application/json" },
      body: JSON.stringify({ text, voice_id: voiceId, container: "wav", stream: false }),
    });
    if (!res.ok) throw new Error(`TTS request failed: ${res.status}`);

    const url = URL.createObjectURL(await res.blob());
    const audio = new Audio(url);
    audioRef.current = audio;
    audio.onplay = () => setSpeaking(true);
    audio.onended = () => {
      setSpeaking(false);
      URL.revokeObjectURL(url);
    };
    await audio.play();
  }, [stop]);

  useEffect(() => stop, [stop]); // stop speaking on unmount

  return { speaking, speakBrowser, speakAssemblyAI, stop };
}

And a component that uses it:

// App.jsx
import { useState } from "react";
import { useSpeech } from "./useSpeech";

export default function App() {
  const [text, setText] = useState("Hello from React text to speech.");
  const { speaking, speakBrowser, speakAssemblyAI, stop } = useSpeech();

  return (
    <div>
      <h1>React Text to Speech</h1>
      <textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} />
      <button onClick={() => speakBrowser(text)}>Speak (browser voice)</button>
      <button onClick={() => speakAssemblyAI(text)}>Speak (AssemblyAI)</button>
      <button onClick={stop} disabled={!speaking}>Stop</button>
    </div>
  );
}

This works in Vite, Next.js (in a client component) or Create React App, as long as the /tts-token route from the previous section is served from the same origin. Two React-specific notes:

  • Don't call speak() during render or in an effect that runs on mount. Browsers block audio without a user gesture, and React's development mode runs effects twice. Trigger speech from event handlers, as above.
  • To offer the browser's voice list, read window.speechSynthesis.getVoices() in an effect and update state on voiceschanged, the same pattern as the plain-JavaScript version.
Explore AssemblyAI text-to-speech

See what AssemblyAI-TTS-1 does with voices, numbers and names, and how it fits next to speech-to-text on one API key.

Explore text-to-speech

Highlight words as they're spoken

Read-along highlighting needs to know when each word is spoken. The browser offers boundary events on SpeechSynthesisUtterance, but support depends on the browser and the voice. AssemblyAI's WebSocket session sends word boundaries: each word with its start and end time in milliseconds. Turn them on with wordBoundaries: true.

import { TextToSpeechSession } from "assemblyai";

const ctx = new AudioContext({ sampleRate: 24000 }); // create inside a click handler
let playhead = 0;

function playPcm(chunk) {
  const pcm = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.byteLength >> 1);
  const buffer = ctx.createBuffer(1, pcm.length, 24000);
  buffer.copyToChannel(Float32Array.from(pcm, (s) => s / 32768), 0);
  const source = ctx.createBufferSource();
  source.buffer = buffer;
  source.connect(ctx.destination);
  playhead = Math.max(playhead, ctx.currentTime);
  source.start(playhead);
  playhead += buffer.duration;
}

const KYLA = "aai-kyla";

async function readAlong(text, token, highlight) {
  const session = new TextToSpeechSession({ token, voiceId: KYLA, wordBoundaries: true });
  let startedAt = 0;

  session.on("wordBoundaries", (event) => {
    for (const w of event.words) {
      const at = startedAt + (w.start - event.audio_start_ms) / 1000;
      setTimeout(() => highlight(w.word), Math.max(0, (at - ctx.currentTime) * 1000));
    }
  });

  await session.connect();
  startedAt = Math.max(playhead, ctx.currentTime);
  for await (const chunk of session.speak(text)) playPcm(chunk);
  await session.close();
}

Word timings arrive just after the request's audio, so schedule the highlights against the time playback started rather than the time they arrive. They're best effort: build the UI so it falls back to no highlighting rather than breaking. The word boundaries docs cover the edge cases, and our explainer on TTS word timestamps covers what else they're good for, like captions and interruption handling.

Web Speech API vs AssemblyAI TTS

Web Speech API (speechSynthesis) AssemblyAI TTS API (AssemblyAI-TTS-1)
Where it runs Browser only Node, the browser (via temporary token) and any HTTP or WebSocket client
Voices Whatever the user's OS and browser provide; differs per device Thousands of voices plus cloned voices; identical on every device
Languages Depends on installed voices English, Spanish, German, French, Italian, Portuguese
Audio output Plays to speakers; no file or stream WAV, MP3, raw PCM, μ-law or A-law, as a file or a stream
Word timings boundary events; support varies by browser and voice Per-word start and end times on the WebSocket session and the events route
Setup None; no key API key on your server; temporary tokens for the browser
Cost Free $15 per 1M characters

Use speechSynthesis for accessibility helpers, prototypes and anything where "good enough, free and offline-capable" wins. Use a TTS API when the voice is part of your product, when you need audio outside the browser, or when names and numbers have to come out right.

Conclusion

Browser text to speech is one object and one method, and it's still the right first step. The interesting part comes after: the moment your app needs to sound the same for every user, read a confirmation code without mangling it, or speak from a server, you've outgrown the OS voice. The code above is designed so that switch is one function call, speakBrowser to speakAssemblyAI, and the rest of your app doesn't notice. If you want the background on how modern models get there, start with what text to speech is and work forward.

Upgrade from speechSynthesis in one function call

Get a free AssemblyAI API key and generate natural speech from Node, the browser or React with the same SDK. $15 per 1M characters, thousands of voices.

Sign up free

Frequently Asked Questions (FAQs)

What is speechSynthesis in JavaScript?

speechSynthesis is the browser's text-to-speech controller, exposed as window.speechSynthesis as part of the Web Speech API. You create a SpeechSynthesisUtterance with the text, optionally set its voice, rate and pitch, and pass it to speechSynthesis.speak(). It needs no library or API key, but it only runs in the browser and uses the operating system's voices.

Why does speechSynthesis sound different in each browser?

speechSynthesis uses the voices the operating system and browser provide, so Chrome on Windows, Safari on iOS and Firefox on Linux each offer a different voice list and quality. The voice list also loads asynchronously, which is why getVoices() can return an empty array until the voiceschanged event fires. A TTS API such as AssemblyAI-TTS-1 gives every user the same voice.

How do I use text to speech in React?

Wrap the speech logic in a custom hook and trigger it from event handlers, not during render. The useSpeech hook in this guide calls window.speechSynthesis.speak() for the free browser voice, or fetches a WAV from the AssemblyAI TTS API with a temporary token for a consistent, natural voice. It also cancels playback when the component unmounts.

Can I call a text-to-speech API from the browser without exposing my API key?

Yes. Mint a short-lived temporary token on your server with client.tts.createTemporaryToken({ expires_in_seconds: 60 }) and send it to the page. The page uses the token in place of the API key, either in the Authorization header of POST /v1/speech or with new TextToSpeechSession({ token }) for streaming. Mint a fresh token per request and keep the expiry short.

How do I get word timestamps to highlight text as it's spoken?

Open an AssemblyAI TTS WebSocket session with wordBoundaries: true and listen for the wordBoundaries event. Each event lists the words with start and end times in milliseconds, which you schedule against the moment playback started. The browser's own boundary events on SpeechSynthesisUtterance exist too, but support varies by browser and voice.

How much does the AssemblyAI text-to-speech API cost?

AssemblyAI text-to-speech costs $15 per 1M characters, billed on the characters you send. Sessions open at once aren't capped; only new sessions per minute are rate-limited, and that limit grows with use on a paid plan. There's a free tier to try it, and the same API key works for AssemblyAI's speech-to-text and LLM Gateway.