Talking Avatar
← Back to BlogIntegration guide

How to Add a Real-Time Talking Avatar to the AssemblyAI Voice Agent API, Step by Step

Published:
Reading time:
8 min
Illustration of giving an AssemblyAI voice agent a face: a microphone card for listening, a chat card for the reply, a voice card with a sound wave, and a browser window where a realistic avatar speaks, linked by a flowing line

To give an AssemblyAI voice agent a real-time face, run a Voice Agent API session on your server, stream the visitor's microphone to it, and pass each reply.audio chunk, 16-bit PCM at 24 kHz, to a Talking Avatar Realistic Avatars session with pushAudio(). AssemblyAI hears, thinks, speaks and handles interruptions in one session, so the server only relays audio: about 100 lines of Node.js.

Note: AssemblyAI's changelog lists the Voice Agent API as deprecated on 28 October 2026, though its docs pages don't mention it. It runs until 1 February 2027 for existing customers while they migrate, so check that your account has it in AssemblyAI's dashboard, and plan your move before then.

How it works

  1. The page streams the visitor's microphone to your server, which sends it to the Voice Agent API as input.audio.
  2. AssemblyAI hears the visitor, decides when they've finished, writes the answer and speaks it, all in one session. Its voice arrives as reply.audio, which goes straight to avatar.pushAudio().
  3. When the visitor talks over Maya, AssemblyAI stops and sends reply.done with status: "interrupted", and your server clears the avatar.

Your AssemblyAI key stays on the server, and the avatar plays Maya's voice in the page in sync with her lips. The same setup works with other voice-to-voice models: see our guides for GPT-Live, Gemini Live and Fish Audio.

What you need

  • An AssemblyAI API key with Voice Agent API access, from AssemblyAI's dashboard.
  • A Talking Avatar account. Sign up to get $1 of free credits; no card is needed.
  • Node.js 22 or later, and headphones for your first test.

Step 1: Add your keys and install

Create a Talking Avatar key in the dashboard under API keys → Create key, and put both keys in a .env file in a new folder. Neither ever reaches the browser.

.env
TALKING_AVATAR_API_KEY=tav_…
ASSEMBLYAI_API_KEY=…

Then install our SDK, Express and ws. AssemblyAI needs no SDK: it's one WebSocket.

npm init -y && npm pkg set type=module && npm install @talkingavatar/sdk express ws

Step 2: Connect to the AssemblyAI Voice Agent API

The prompt sets who Maya is. Keep answers short: this is a conversation.

prompt.txt
You are Maya, a warm, helpful guide on Acme's website, talking with a visitor out loud.
Keep every answer to one or two short sentences, then let them talk.
Speak in plain sentences: no lists, headings, links, emoji or symbols.
If you don't know something, say so, and offer to put them in touch with the team.

The server serves the page, starts an avatar for each visitor, opens their voice agent session and relays the audio both ways.

server.js
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import express from "express";
import { WebSocket, WebSocketServer } from "ws";
import { LiveAvatar } from "@talkingavatar/sdk/server";

const { TALKING_AVATAR_API_KEY, ASSEMBLYAI_API_KEY } = process.env;
const avatars = new Map(); // conversation ID → LiveAvatar
const RATE = 24000; // the Voice Agent API's audio both ways: 16-bit PCM at 24 kHz, which the avatar takes as it is

// The voice agent's settings, sent once when its session opens. The voice can't change after that.
const SESSION = {
  system_prompt: readFileSync("prompt.txt", "utf8"),
  greeting: "Hi, I'm Maya. What can I help you with today?",
  output: { voice: "alba" },
};

const app = express()
  .use(express.json())
  .use(express.static("public"))
  .use("/sdk", express.static("node_modules/@talkingavatar/sdk/dist")); // the browser SDK, no bundler needed

// The page's WebRTC route: plays one conversation's avatar.
app.post("/avatar/:id", async (req, res) => {
  const avatar = avatars.get(req.params.id);
  if (!avatar) return res.status(404).json({ error: "No such conversation" });
  try { res.json(await avatar.handleView(req.body)); }
  catch (error) { res.status(503).json({ error: error.message }); }
});

const server = app.listen(3000, (error) => {
  if (!error) console.log("Open http://localhost:3000"); // on an error, such as the port in use, Node prints it and exits
});

// One WebSocket per visitor: their microphone in, the conversation's state out.
new WebSocketServer({ server, path: "/conversation" }).on("connection", async (browser) => {
  const id = randomUUID();
  let avatar, agent, ready = false, ended = false, problem = "";

  const end = (reason) => {
    if (ended) return;
    ended = true;
    // session.end stops AssemblyAI's billing now; only closing the socket keeps the session, billed, for 30 seconds.
    if (agent?.readyState === WebSocket.OPEN) agent.send(JSON.stringify({ type: "session.end" }));
    agent?.close();
    avatar?.close(); // billing stops
    avatars.delete(id);
    if (browser.readyState === WebSocket.OPEN) {
      browser.send(JSON.stringify({ type: "ended", reason }));
      browser.close();
    }
  };
  browser.on("close", () => end("The visitor left"));

  // 1. Start the avatar.
  try {
    avatar = await LiveAvatar.start({ apiKey: TALKING_AVATAR_API_KEY, avatar: "ava7", sampleRate: RATE });
  } catch (error) {
    return end("The avatar didn't start: " + error.message);
  }
  if (ended) return avatar.close(); // the visitor left while it started
  avatars.set(id, avatar);
  avatar.on("close", (code) => end("The avatar session ended (" + code + ")")); // 4002: out of credits
  browser.send(JSON.stringify({ type: "session", id }));

  const onEvent = (raw) => {
    let event;
    try { event = JSON.parse(raw.toString()); } catch { return; }
    if (ended) return;
    if (event.type === "session.ready") {
      ready = true; // the greeting is on its way: start the microphone
      browser.send(JSON.stringify({ type: "listen", sampleRate: RATE }));
    }
    // 3. Maya's voice: base64 16-bit PCM at 24 kHz, straight to the avatar.
    if (event.type === "reply.audio") avatar.pushAudio(event.data);
    // 5. The visitor talked over Maya, and the agent stopped: drop what the avatar hasn't said yet.
    if (event.type === "reply.done" && event.status === "interrupted") avatar.clear().catch(() => {});
    if (event.type === "session.error") {
      problem = event.message;
      console.error("AssemblyAI: " + event.code + ": " + event.message);
    }
  };

  browser.on("message", (data, isBinary) => {
    // 4. The visitor's microphone, already 16-bit PCM at 24 kHz. Until the session is ready, it's dropped.
    if (isBinary) {
      if (ready && !ended) agent.send(JSON.stringify({ type: "input.audio", audio: data.toString("base64") }));
      return;
    }
    let message;
    try { message = JSON.parse(data.toString()); }
    catch { return end("Invalid browser message"); }
    if (!message || typeof message !== "object" || Array.isArray(message) || typeof message.type !== "string") return end("Invalid browser message");
    if (message.type !== "ready" || agent || ended) return;

    // 2. The visitor can see and hear the avatar: open the voice agent. Maya greets them once it's ready.
    agent = new WebSocket("wss://agents.assemblyai.com/v1/ws", { headers: { Authorization: ASSEMBLYAI_API_KEY } });
    agent.on("open", () => agent.send(JSON.stringify({ type: "session.update", session: SESSION })));
    agent.on("message", onEvent);
    agent.on("error", (error) => { problem ||= error.message; }); // such as a refused connection; the close follows
    agent.on("close", () => end(problem ? "AssemblyAI: " + problem : "The conversation ended"));
  });
});
  • 1. Starts one avatar session per visitor, at 24 kHz. It's billed per second until close().
  • 2. Opens the Voice Agent API once the page reports the avatar as live, and sends session.update with the prompt, the greeting and the voice. Both sides default to 16-bit PCM at 24 kHz, so there's no audio format to set.
  • 3. Passes each reply.audio chunk to pushAudio() as it is.
  • 4. Sends the microphone only after session.ready, as AssemblyAI asks.
  • 5. Clears the avatar on an interrupted reply, and sends session.end when the visitor leaves: closing the socket alone keeps the session open, and billed, for 30 seconds.

ava7 is Maya, one of our library avatars, and alba is one of AssemblyAI's voices. Any voice works with any avatar, your own custom avatar included.

Step 3: Add the page

LiveAvatarView plays the avatar's video and voice in sync, and a small AudioWorklet streams the microphone as 16-bit PCM at the rate the server asks for, 24 kHz here. Save these three files in public/.

public/index.html
<!doctype html>
<meta charset="utf-8">
<title>AssemblyAI with a Talking Avatar</title>
<div id="avatar" style="width: 640px; max-width: 100%; aspect-ratio: 16 / 9; background: #111"></div>
<p>
  <button id="start">Talk to Maya</button>
  <button id="unmute" hidden>Turn sound on</button>
  <span id="status"></span>
</p>
<script type="module" src="/page.js"></script>
public/page.js and public/mic-worklet.js

The same two files in all our voice agent guides: only the server changes between them.

public/page.js
import { LiveAvatarView } from "/sdk/live.js";

const start = document.getElementById("start");
const unmute = document.getElementById("unmute");
const status = document.getElementById("status");

start.onclick = async () => {
  start.disabled = true;
  // Echo cancellation keeps the avatar's own voice out of the microphone.
  let mic;
  try {
    mic = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } });
  } catch (error) {
    status.textContent = "Microphone unavailable: " + error.message;
    start.disabled = false;
    return;
  }
  const socket = new WebSocket(location.origin.replace("http", "ws") + "/conversation");
  let view, audio, ready = false;

  socket.onmessage = async ({ data }) => {
    const message = JSON.parse(data);
    if (message.type === "session") {
      // Plays the avatar's video and the agent's voice.
      view = new LiveAvatarView({
        container: document.getElementById("avatar"),
        endpoint: "/avatar/" + message.id,
        onStatus: (s) => {
          status.textContent = s;
          unmute.hidden = s !== "muted";
          if ((s === "live" || s === "muted") && !ready) {
            ready = true;
            socket.send(JSON.stringify({ type: "ready" }));
          }
        },
      });
      unmute.onclick = () => view.unmute();
      view.connect();
    }
    if (message.type === "listen") {
      audio = await streamMicrophone(mic, message.sampleRate, (pcm) => {
        if (socket.readyState === WebSocket.OPEN) socket.send(pcm);
      });
    }
    if (message.type === "ended") {
      view?.disconnect(); // first, so its "closed" status doesn't replace the reason
      status.textContent = message.reason;
    }
  };

  socket.onclose = () => {
    view?.disconnect();
    view?.video.remove();
    audio?.close();
    mic.getTracks().forEach((track) => track.stop());
    start.disabled = false;
  };
};

// Sends the microphone as 16-bit PCM at the agent's input rate, in 100 ms chunks.
async function streamMicrophone(stream, rate, send) {
  const context = new AudioContext();
  await context.audioWorklet.addModule("/mic-worklet.js");
  const node = new AudioWorkletNode(context, "mic", { processorOptions: { rate } });
  node.port.onmessage = ({ data }) => send(data);
  context.createMediaStreamSource(stream).connect(node).connect(context.destination); // the node outputs silence
  await context.resume();
  return context;
}
public/mic-worklet.js
// Resamples the microphone to the agent's input rate and posts 16-bit PCM in 100 ms chunks.
class Mic extends AudioWorkletProcessor {
  constructor({ processorOptions }) {
    super();
    this.step = sampleRate / processorOptions.rate; // input samples per output sample
    this.at = 0;                                     // read position; -1 is the previous block's last sample
    this.last = 0;
    this.chunk = new Int16Array(processorOptions.rate / 10);
    this.length = 0;
  }

  process([input]) {
    const samples = input[0];
    if (!samples) return true;
    while (this.at < samples.length - 1) {
      const i = Math.floor(this.at);
      const a = i < 0 ? this.last : samples[i];
      const value = a + (samples[i + 1] - a) * (this.at - i);
      this.chunk[this.length++] = Math.max(-1, Math.min(1, value)) * 0x7fff;
      if (this.length === this.chunk.length) {
        const out = this.chunk.slice();
        this.port.postMessage(out.buffer, [out.buffer]);
        this.length = 0;
      }
      this.at += this.step;
    }
    this.at -= samples.length;
    this.last = samples[samples.length - 1];
    return true;
  }
}

registerProcessor("mic", Mic);

Step 4: Run it

node --env-file=.env server.js

Open http://localhost:3000, click Talk to Maya and allow the microphone. Maya greets you, then listens. Ask her something, and talk over her answer to check that she stops. The avatar starts speaking less than 250 ms after AssemblyAI's audio reaches it.

To tune how readily Maya yields, set input.turn_detection in session.update; see AssemblyAI's turn detection and interruptions and our Interruptions docs.

What it costs

Talking Avatar Realistic Avatars cost $0.02 a minute, billed per second, with no subscription; high-volume contracts go as low as $0.005 a minute. The Voice Agent API is one rate for speech recognition, the LLM and the voice, but AssemblyAI's pricing page no longer lists it (checked 24 November 2026), so check your rate in its dashboard.

Monthly cost of an AssemblyAI voice agent with a realistic avatar at 1,000 minutes
At 1,000 minutes a monthCost
Avatar (Talking Avatar Realistic Avatars)$20
AssemblyAI Voice Agent APIYour AssemblyAI rate, not published

Don't want to run a server at all? Talking Avatar Voice Agents are complete voice agents on a realistic avatar, set up in our dashboard without code, for $0.06 a minute with the avatar included at no extra cost.

Before you go live

  • Protect /conversation. Every connection starts a billed avatar session and a billed voice agent session, so put it behind your app's login and limit how many each user can open.
  • Serve the page over HTTPS. Browsers only allow the microphone on secure pages (localhost is the exception). Keep echoCancellation on, so Maya doesn't hear herself.
  • Plan your move before 1 February 2027. AssemblyAI's replacement is its streaming speech-to-text, LLM Gateway and Text-to-Speech API, wired together by you; the avatar side of this guide stays the same.
  • Set spending limits. In our dashboard, set a monthly limit and auto top-up; a session ends with close code 4002 when credits run out. One avatar session lasts up to 3 hours, and a small “Powered by Talking Avatar” watermark shows unless you remove it for $19 a month.

Read the full production checklist →

Troubleshooting

“AssemblyAI: Missing or invalid Authorization token”
Check ASSEMBLYAI_API_KEY. The key goes in the Authorization header as it is, with no Bearer.
“The avatar didn’t start: talking-avatar: invalid or missing API key”
Check TALKING_AVATAR_API_KEY, or create a new key in the dashboard.
The avatar moves but makes no sound
The browser blocked sound (status muted). Click Turn sound on, which calls view.unmute().
Maya talks over herself or keeps stopping
Her voice is reaching the microphone. Keep echoCancellation on, and test with headphones.

Methodology

How we wrote this guide

We build Talking Avatar Realistic Avatars, so the avatar side follows our SDK documentation for @talkingavatar/sdk 0.1.0. The AssemblyAI side follows its Voice Agent API documentation (events, audio format, voices and deployment), its pricing page and its changelog, read on 24 November 2026. On 24 November 2026 we ran the guide's files as written (on another port) against live Voice Agent API and avatar sessions, with Chrome and a recorded voice as the microphone: Maya greeted, answered a spoken question, stopped when talked over (AssemblyAI sent an interrupted reply.done and the server cleared the avatar), answered again, and both sessions closed when the page did. Its message flow also has automated tests against a simulated session. The avatar latency figure is our own measurement in production.

Frequently asked questions

Does AssemblyAI have a voice-to-voice API?

Yes, the Voice Agent API: one WebSocket that takes the caller's audio and returns the agent's spoken reply, with speech recognition, the LLM, the voice, turn detection and interruptions inside. AssemblyAI deprecated it on 28 October 2026, and it runs until 1 February 2027 for existing customers while they migrate.

How do I add an avatar to an AssemblyAI voice agent?

Run the Voice Agent API session on your server, pass each reply.audio chunk (base64 16-bit PCM at 24 kHz) to a Talking Avatar Realistic Avatars session with pushAudio(), call clear() when reply.done arrives with status "interrupted", and show the avatar on your page with LiveAvatarView.

Do I need a separate speech-to-text, LLM or TTS?

No. The Voice Agent API hears, thinks and speaks in one session, so your server only relays audio: the microphone in, the voice out to the avatar.

What happens after the Voice Agent API retires?

AssemblyAI points voice agents to its streaming speech-to-text (AssemblyAI-STT-3.7-Realtime-Agent), its LLM Gateway and its Text-to-Speech API. The avatar side doesn't change: the voice still goes to pushAudio(), and an interruption still calls clear().

Which voices and languages work?

Any Voice Agent API voice, set in session.update: alba, eve, george, jane, jean, mary and michael (American), anna, charles, paul and vera (British), and native voices for Italian, Spanish, German, Portuguese and French. The avatar lip-syncs whatever the agent says.

What does an AssemblyAI avatar cost?

The avatar is $0.02 a minute, billed per second. AssemblyAI no longer publishes a price for the Voice Agent API, which covers speech recognition, the LLM and the voice in one rate, so check your rate in AssemblyAI's dashboard.

Can the avatar look like me?

Yes. Pick any avatar from our library, or order a custom avatar of a real person, with their consent, for $199 one time. Use its ID in LiveAvatar.start().

Mukul Munjal

About me

Mukul Munjal

Co-founder, Talking Avatar

I'm Mukul Munjal, co-founder of Talking Avatar. I have 7 years of experience in engineering, 3 of them building voice agents, and I handle the optimisation of our voice agents. We built Talking Avatar to give our own AI interviewers a face.

Connect with me on LinkedInThe team behind Talking Avatar

Evaluating tools?

Compare your options

See how the platforms in this article compare on pricing, features and fit.

Realistic avatars from $0.02 a minute, billed per second. No subscription.

Avatar API prices comparedGet API key