How to Add a Real-Time Talking Avatar to the Gemini Live API (Gemini 3.8 Live), Step by Step
- Published:
- Reading time:
- 10 min
To give Gemini 3.8 Live a real-time face, run its Live API session on your own server with @google/genai, send the visitor's microphone as 16-bit PCM at 16 kHz, and pass every audio part Gemini returns, 16-bit PCM at 24 kHz, to a Talking Avatar Realistic Avatars session with pushAudio(). Gemini hears, thinks, speaks and handles interruptions itself; with the avatar it costs about $0.034 a minute.
How it works
- The page streams the visitor's microphone to your server, which sends it to Gemini 3.8 Live as 16-bit PCM at 16 kHz with
sendRealtimeInput(). - Gemini hears the visitor, decides when they've finished, answers and speaks, all in one session. Its voice, 16-bit PCM at 24 kHz, goes straight to
avatar.pushAudio(). - When the visitor talks over Amara, Gemini stops and sends
serverContent.interrupted, and your server clears the avatar.
Your Gemini key stays on the server, and the avatar plays Amara's voice in the page in sync with her lips. On Vertex AI, Google can also render its own avatar; see how the two compare. The same setup works with other voice-to-voice models: see our guides for GPT-Live, Fish Audio and AssemblyAI.
What you need
- A Gemini API key from Google AI Studio, on the paid tier for real visitors.
- 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.
TALKING_AVATAR_API_KEY=tav_…
GEMINI_API_KEY=…Then install our SDK, Google's @google/genai, Express and ws:
npm init -y && npm pkg set type=module && npm install @talkingavatar/sdk @google/genai express wsStep 2: Connect to the Gemini Live API
The prompt goes in as Gemini's system instruction. Keep answers short: this is a conversation.
You are Amara, 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 Gemini 3.8 Live session and relays the audio both ways.
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import express from "express";
import { WebSocket, WebSocketServer } from "ws";
import { GoogleGenAI, Modality } from "@google/genai";
import { LiveAvatar } from "@talkingavatar/sdk/server";
const { TALKING_AVATAR_API_KEY, GEMINI_API_KEY } = process.env;
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY, httpOptions: { apiVersion: "v1beta" } });
const avatars = new Map(); // conversation ID → LiveAvatar
const MIC_RATE = 16000; // what Gemini Live takes
const VOICE_RATE = 24000; // what Gemini Live sends, and the avatar takes as it is
// Gemini 3.8 Live's settings, fixed for the whole session.
const MODEL = "gemini-3.8-live";
const CONFIG = {
responseModalities: [Modality.AUDIO],
systemInstruction: readFileSync("prompt.txt", "utf8"),
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } },
};
const GREET = "The visitor just joined. Greet them in one short sentence as Amara, and ask how you can help.";
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, live, connecting = false, ended = false;
const end = (reason) => {
if (ended) return;
ended = true;
live?.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: "ava1", sampleRate: VOICE_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 onMessage = (message) => {
const content = message.serverContent;
if (!content || ended) return;
// 5. The visitor talked over Amara, and Gemini stopped: drop what the avatar hasn't said yet.
if (content.interrupted) avatar.clear().catch(() => {});
// 3. Gemini's voice: base64 16-bit PCM at 24 kHz, straight to the avatar. One message can carry several parts.
for (const part of content.modelTurn?.parts ?? []) {
if (part.inlineData?.data) avatar.pushAudio(part.inlineData.data);
}
};
browser.on("message", async (data, isBinary) => {
// 4. The visitor's microphone, already 16-bit PCM at 16 kHz.
if (isBinary) {
if (live && !ended) live.sendRealtimeInput({ audio: { data: data.toString("base64"), mimeType: "audio/pcm;rate=16000" } });
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" || connecting || ended) return;
// 2. The visitor can see and hear the avatar: start Gemini Live, and ask it to greet them.
connecting = true;
let session;
try {
session = await ai.live.connect({
model: MODEL,
config: CONFIG,
callbacks: {
onmessage: onMessage,
onerror: (error) => console.error("Gemini Live: " + error.message),
onclose: (event) => end("The conversation ended" + (event.reason ? ": " + event.reason : "")),
},
});
} catch (error) {
return end("Gemini Live: " + error.message);
}
if (ended) return session.close(); // the visitor left while it connected
live = session;
browser.send(JSON.stringify({ type: "listen", sampleRate: MIC_RATE }));
live.sendRealtimeInput({ text: GREET });
});
});
- 1. Starts one avatar session per visitor, at 24 kHz. It's billed per second until
close(). - 2. Opens the Gemini session once the page reports the avatar as live, so the greeting isn't spoken to an empty page. The model, prompt and voice are fixed when it opens.
- 3. Passes every audio part of every message to
pushAudio(): one message can carry several parts, audio and transcript together. - 4. Sends the microphone as base64 PCM with the MIME type
audio/pcm;rate=16000. - 5. Calls
avatar.clear()when Gemini reports an interruption, so the avatar stops with the voice.
ava1 is Amara, one of our library avatars, and Kore is one of Gemini's prebuilt voices. Any Gemini 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, 16 kHz here. Save these three files in public/.
<!doctype html>
<meta charset="utf-8">
<title>Gemini Live 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 Amara</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.
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;
}
// 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.jsOpen http://localhost:3000, click Talk to Amara and allow the microphone. Amara 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 Gemini's audio reaches it.
To tune how readily Amara yields, set startOfSpeechSensitivity and silenceDurationMs under realtimeInputConfig.automaticActivityDetection; see Live API capabilities and our Interruptions docs.
Gemini's own Live Avatar, or Talking Avatar?
On Google Cloud's Gemini Enterprise Agent Platform (Vertex AI), Gemini 3.8 Live can also render a talking avatar itself: Google calls it Live Avatar. With a Gemini API key from AI Studio, it outputs audio and text only. Here's how the two compare, from Google's documentation as of 24 November 2026:
| Question | Gemini Live Avatar | Talking Avatar Realistic Avatars |
|---|---|---|
| Where it runs | Google Cloud's Gemini Enterprise Agent Platform (Vertex AI), with OAuth. The Gemini API with an AI Studio key lists audio and text output only. | Any Gemini 3.8 Live session, with an AI Studio key or on Vertex AI, and any other voice agent or TTS. |
| Faces | Prebuilt avatars. Custom avatars from a reference image are for select customers only, through Google Cloud's account team. | A library of photorealistic avatars, or a custom avatar of a real person, with their consent, for $199 one time. |
| How it reaches your page | 24 FPS video from the model, in the Live API session. | Video and voice streamed to your page over WebRTC, or into your LiveKit room. |
| Price | About $0.37 per speaking minute for avatar video ($1.00 per 1M tokens), plus voice and model tokens. | $0.02 a minute, billed per second. |
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. On its paid tier, Gemini 3.8 Live charges $0.005 a minute of audio in and $0.018 a minute of audio out, with text and tools on top (Google's pricing, checked 24 November 2026).
| At 1,000 minutes a month | Cost |
|---|---|
| Avatar (Talking Avatar Realistic Avatars) | $20 |
| Gemini audio in (the microphone, all the time) | $5 |
| Gemini audio out (Amara speaking half the time) | $9 |
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 Gemini 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
echoCancellationon, so Amara doesn't hear herself. - Plan for session limits. Without context window compression, a Gemini audio session lasts up to 15 minutes, and one connection about 10. For longer calls, use context window compression and session resumption.
- Use Gemini's paid tier, and set spending limits. On the free tier, Google may use your data to improve its products. 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.
Troubleshooting
- “Gemini Live: API key not valid” on the page
- Check
GEMINI_API_KEY, or create a new key in Google AI Studio. - “The conversation ended: …” after about 10 minutes
- Gemini closed the connection at its time limit. Use session resumption to continue on a new connection; see session management.
- The avatar moves but makes no sound
- The browser blocked sound (status
muted). Click Turn sound on, which callsview.unmute(). - Amara doesn’t greet you
- The greeting is a text message asking Gemini to say hello, and Gemini 3.8 Live decides when to speak. Say hello, and she answers.
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 Gemini side follows Google's Gemini 3.8 Live and Live API documentation, its pricing, and Google Cloud's Live Avatar documentation, read on 24 November 2026. On 24 November 2026 we ran the guide's files as written (on another port) against live Gemini 3.8 Live and avatar sessions, with Chrome and a recorded voice as the microphone: Amara greeted, answered a spoken question, stopped when talked over (Gemini sent interrupted 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 Gemini Live have an avatar?
On Google Cloud's Vertex AI, yes: Gemini 3.8 Live can render a Live Avatar from prebuilt avatars, and custom ones for select customers. Through the Gemini API with an AI Studio key, it outputs audio and text only. To give that session a face, pass its audio to a real-time avatar, as this guide does.
How do I add an avatar to the Gemini Live API?
Run the Gemini 3.8 Live session on your server with @google/genai, with responseModalities set to audio. Pass every inlineData audio part of each message, base64 PCM at 24 kHz, to a Talking Avatar Realistic Avatars session with pushAudio(), call clear() when serverContent.interrupted arrives, and show the avatar on your page with LiveAvatarView.
Do I need a separate speech-to-text, LLM or TTS?
No. Gemini 3.8 Live is audio in and audio out: it hears the visitor, decides when they've finished, answers and speaks in one session. It also handles interruptions, so the only thing your server does on one is clear the avatar.
Can I use Vertex AI instead of an AI Studio key?
Yes. Create the client with new GoogleGenAI({ vertexai: true, project, location }) and the rest of the server stays the same. On Vertex AI you could also use Gemini's own Live Avatar; Talking Avatar is for a face from our photorealistic library or your own custom avatar, streamed to your page over WebRTC.
How long can a conversation last?
Without context window compression, a Gemini audio session lasts up to 15 minutes, and one connection about 10. For longer calls, turn on context window compression and resume the session on a new connection; the avatar session itself lasts up to 3 hours.
Which voices and languages work?
Any of Gemini's prebuilt voices, such as Kore, set in speechConfig, and the Live API's 70 languages. The avatar lip-syncs whatever Gemini says, in any language.
What does a Gemini Live avatar cost?
Gemini 3.8 Live charges $0.005 a minute of audio in and $0.018 a minute of audio out on its paid tier, and the avatar is $0.02 a minute: about $0.034 a minute together if Amara speaks half the time.
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().

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.
Evaluating tools?
Compare your options
See how the platforms in this article compare on pricing, features and fit.
HeyGen LiveAvatar
Anam
Tavus
Realistic avatars from $0.02 a minute, billed per second. No subscription.
Avatar API prices comparedGet API key