495
English 繁體中文 简体中文

如何用 LiveKit + Synthesia 数字人(版本 1)?

林邦源博士 · AI 笔记 · 2026 年 11 月 4 日 · 约 6 分钟阅读

只能输出文字或一个没有脸的声音的语音代理已经很有用——但如果代理有 一张脸,感觉就会像在跟真人说话。 Synthesia 能生成逼真的 AI 数字人,实时说话、实时对口型。 LiveKit 则把数字人和语音代理流水线绑在一起:麦克风 → 语音识别 → LLM → 文字转语音 → 数字人。

这篇笔记带你跑通最小可运行演示:浏览器里一个视频框、一个按钮,数字人 Lin 扮演一家 虚构餐厅的迎宾员,回答你什么时候开门。这是版本 1——故意做得很精简, 让每一行代码都容易看懂。

整条流水线

浏览器麦克风 → VAD → STT → LLM → TTS → Synthesia 数字人 → 浏览器视频

五块组件通过 LiveKit 的实时传输连在一起。VAD(语音活动检测) 负责监听你什么时候开口、什么时候停下,STT 把语音转文字, LLM 负责回答,TTS 把回答念出来, Synthesia 渲染出跟语音同步的脸。 全部跑在 LiveKit Cloud 上,不需要你自己搭服务器。

准备工作

设置 LiveKit Cloud

在 cloud.livekit.io 注册登录。进入控制台,点 Projects → Create Project, 打开项目后点 Keys,复制这三个值:

设置 Synthesia

登录 app.synthesia.io。 进入 Avatars,选一个或新建一个数字人——每个数字人都有一个 UUID, 打开它时 URL 里就能看到(像 3190429b-1eda-4151-bf24-96162e405840), 这就是 SYNTHESIA_AVATAR_ID。

然后到 API Keys 创建一把密钥——这就是 SYNTHESIA_API_KEY。

创建 .env

在你的项目文件夹里新建一个文件,命名为 .env,填入以下五行:

LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=APIxxxxxxxxxxxxx
LIVEKIT_API_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SYNTHESIA_API_KEY=syn_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SYNTHESIA_AVATAR_ID=3190429b-1eda-4151-bf24-96162e405840

注意:绝对不要把 .env 传到 GitHub 或任何公开网站——里面是你的真实凭证。

在自己电脑上运行

下载 zip 文件, 解压到一个文件夹里。zip 里包含 agent.py、server.py、 index.html 和 pyproject.toml。 把你的 .env 凭证文件放到同一文件夹(如上面所示)。然后在 Visual Studio Code 里打开这个文件夹, 在两个不同的终端窗口里分别运行:

终端 1 —— 语音代理 + 数字人引擎:

uv sync
uv run agent.py dev

终端 2 —— 浏览器页面的 Web 服务器:

uv run server.py

uv sync 只需要第一次跑——它会自动装 Python 3.13 和所有依赖包。之后每次只要开两个终端分别运行 agent.py 和 server.py 就行。

在浏览器里打开页面

两个终端都跑起来之后,在 Chrome、Safari 或 Edge 里打开 http://127.0.0.1:8080, 点 Start,允许麦克风权限,然后等个几秒钟让代理和数字人加入房间。 你应该能看到 Lin 跟你打招呼——点一下麦克风图标试试问它一个问题,比如「你们几点开门?」。

zip 里的文件

pyproject.toml

[project]
name = "folder-ai-avatar"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
    "aiohttp>=3.14.4",
    "livekit-agents[openai,silero]~=1.8",
    "livekit-plugins-synthesia~=1.8",
    "python-dotenv>=1.2.4",
]

[build-system]
requires = ["uv_build>=0.12.11,<0.13.0"]
build-backend = "uv_build"

agent.py

import asyncio
import os
from pathlib import Path

from dotenv import load_dotenv
from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, cli, inference
from livekit.plugins import silero, synthesia

load_dotenv(dotenv_path=Path(__file__).parent / ".env")

AGENT_NAME = "avatar-demo"
AVATAR_ID = os.getenv("SYNTHESIA_AVATAR_ID") or "3190429b-1eda-4151-bf24-96162e405840"
VOICE_ID = "db6b0ed5-d5d3-463d-ae85-518a07d3c2b4"

INSTRUCTIONS = """\
You are Lin, the host at YouFantasy, a made-up restaurant. You are a real-time
avatar in a spoken conversation, so answer in one short sentence and never use
markdown, lists, or URLs.

YouFantasy is open every day from 9am to 10pm.

That is the only thing you know. If the guest asks about anything else, say
kindly that for now you can only help with our opening hours."""


def prewarm(proc) -> None:
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext) -> None:
    await ctx.connect()

    session = AgentSession(
        vad=ctx.proc.userdata["vad"],
        stt=inference.STT(model="cartesia/ink-2"),
        llm=inference.LLM(model="openai/gpt-4.1-mini"),
        tts=inference.TTS(model="cartesia/sonic-3.6", voice=VOICE_ID),
        turn_handling={"turn_detection": "stt"},
    )

    avatar = synthesia.AvatarSession(
        synthesia.AvatarConfig(avatar_ids=[AVATAR_ID]),
        join_timeout=60.0,
    )
    for attempt in range(3):
        try:
            await avatar.start(session, room=ctx.room)
            break
        except synthesia.SynthesiaError as e:
            if not e.retryable or attempt == 2:
                raise
            await asyncio.sleep(2)

    await session.start(agent=Agent(instructions=INSTRUCTIONS), room=ctx.room)
    session.generate_reply(
        instructions="Welcome the guest to YouFantasy and invite them to ask about our opening hours, in one short sentence."
    )


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm, agent_name=AGENT_NAME, port=8081))

server.py

import os
import uuid
from datetime import timedelta
from pathlib import Path

from aiohttp import web
from dotenv import load_dotenv
from livekit import api

load_dotenv(dotenv_path=Path(__file__).parent / ".env")

AGENT_NAME = "avatar-demo"


async def token(request: web.Request) -> web.Response:
    room = f"avatar-demo-{uuid.uuid4().hex[:8]}"
    jwt = (
        api.AccessToken()
        .with_identity(f"user-{uuid.uuid4().hex[:8]}")
        .with_ttl(timedelta(minutes=15))
        .with_grants(api.VideoGrants(room_join=True, room=room))
        .with_room_config(
            api.RoomConfiguration(
                sync_streams=True,
                agents=[api.RoomAgentDispatch(agent_name=AGENT_NAME)],
            )
        )
        .to_jwt()
    )
    return web.json_response({"url": os.environ["LIVEKIT_URL"], "token": jwt})


async def index(request: web.Request) -> web.FileResponse:
    return web.FileResponse(
        Path(__file__).parent / "index.html", headers={"Cache-Control": "no-store"}
    )


app = web.Application()
app.router.add_get("/", index)
app.router.add_get("/token", token)

if __name__ == "__main__":
    web.run_app(app, host="127.0.0.1", port=8080)

index.html

<!doctype html>
<html lang="en">
... (same as in English version above)

工作原理,大白话解释

两个程序,两个终端。 agent.py 是语音 + 数字人引擎——它加入 LiveKit 房间、监听麦克风、负责回答、驱动数字人。 server.py 是一个小小的 aiohttp Web 服务器,负责提供页面,并在每次访问时签发一个短期有效的 LiveKit 访问令牌(这样凭证就不会写死在 HTML 里)。 两个要分开启动,因为各自占用不同端口。

浏览器完全不知道数字人这回事。 index.html 只是加入一个 LiveKit 房间、播放所有收到的视频轨道—— 它不关心轨道来自真实摄像头还是 Synthesia 数字人。数字人从 agent 内部把自己的视频流传出来, 房间配置里 sync_streams=True 保证嘴型和音频同步。

冷启动自动重试。 Synthesia 服务偶尔会花几秒钟才能拉起一个数字人会话,所以 agent 会最多重试三次再放弃。 这就是为什么第一次点 Start 会感觉慢——不是坏了,是在热身。

版本 1 的局限

延伸阅读