> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vivix.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 接入 TRTC

以下 TRTC 示例包含服务端创建和关闭会话、控制 WebSocket，以及浏览器播放。请使用 Node.js 22。API 密钥保存在服务端，页面只接收会话凭证。该本地服务器绑定 localhost，并且同一时间只管理一个会话。

## 1. 准备文件

```bash theme={null}
npm init -y
npm install trtc-sdk-v5@^5.9.0
npm install --save-dev esbuild
```

将以下三个文件保存在同一个目录中。如果要直接启动新会话，还需保存[快速开始](https://docs.vivix.ai/cn/streaming-avatar/get-started/quickstart.md)中的 `session.json`。

### server.mjs

```javascript wrap theme={null}
import http from "node:http";
import { readFile } from "node:fs/promises";
const key = process.env.VIVIX_API_KEY;
if (!key) throw new Error("Set VIVIX_API_KEY");
const responseFile = process.env.SESSION_RESPONSE_FILE;
const config = responseFile ? null : JSON.parse(await readFile("session.json", "utf8"));
let imported = false;
let sessionId;
let starting = false;
async function api(path, body) {
  const res = await fetch(`https://api.vivix.ai/v1/${path}`, {
    method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
  const data = await res.json();
  if (!res.ok || data.code !== 0) throw new Error(data.message || `HTTP ${res.status}`);
  return data.data;
}
http.createServer(async (req, res) => {
  try {
    if (req.method === "POST" && req.url === "/session") {
      if (starting || sessionId) { res.writeHead(409); return res.end("Close the current session first"); }
      starting = true;
      try {
        let s;
        if (responseFile) {
          if (imported) throw new Error("This saved session has already been used. Create a new session to restart.");
          const envelope = JSON.parse(await readFile(responseFile, "utf8"));
          if (envelope.code !== 0 || !envelope.data?.session_id) throw new Error("Expected a successful Create Session response");
          s = envelope.data;
          imported = true;
        } else {
          s = await api("realtime-avatar/sessions", config);
        }
        sessionId = s.session_id;
        res.setHeader("Content-Type", "application/json");
        return res.end(JSON.stringify(s));
      } finally { starting = false; }
    }
    if (req.method === "POST" && req.url === "/close") {
      if (sessionId) {
        const result = await api(`realtime-avatar/sessions/${encodeURIComponent(sessionId)}/close`, {});
        if (!["closing", "closed"].includes(result.status)) throw new Error(`Session status: ${result.status}`);
      }
      sessionId = undefined;
      return res.end("Session closure requested");
    }
    const files = { "/": ["index.html", "text/html"], "/app.js": ["app.js", "text/javascript"] };
    const file = req.method === "GET" && files[req.url];
    if (!file) { res.writeHead(404); return res.end(); }
    res.setHeader("Content-Type", file[1]);
    res.end(await readFile(file[0]));
  } catch (e) { res.writeHead(500); res.end(String(e.message)); }
}).listen(3000, "127.0.0.1", () => console.log("http://localhost:3000"));
```

### index.html

```html wrap theme={null}
<!doctype html><html lang="en"><meta charset="utf-8">
<title>Avatar player</title>
<button id="start">Start</button><button id="stop">Stop</button>
<button id="sound" hidden>Enable sound</button>
<p id="status">Ready</p><div id="video" style="width:360px;height:640px;background:#111"></div>
<script src="/app.js"></script></html>
```

### main.js

```javascript wrap theme={null}
import TRTC from "trtc-sdk-v5";
async function connect(s) {
  const m = s.delivery.media.trtc;
  if (!m) throw new Error("Expected TRTC credentials");
  const rtc = TRTC.create();
  const sound = document.querySelector("#sound");
  const resumes = new Set();
  rtc.on(TRTC.EVENT.AUTOPLAY_FAILED, event => {
    resumes.add(event.resume);
    sound.hidden = false;
  });
  sound.onclick = async () => {
    try {
      await Promise.all([...resumes].map(resume => resume()));
      resumes.clear();
      sound.hidden = true;
    } catch (e) { status.textContent = `Playback blocked: ${e.message}`; }
  };
  cleanup = async () => { sound.hidden = true; sound.onclick = null; resumes.clear(); try { await rtc.exitRoom(); } finally { rtc.destroy(); } };
  rtc.on(TRTC.EVENT.ERROR, e => { status.textContent = String(e.message || e); });
  rtc.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, ({userId, streamType}) => {
    if (userId === m.publisher_user_id) rtc.startRemoteVideo({userId, streamType, view: "video"})
      .catch(e => { status.textContent = e.message; });
  });
  rtc.on(TRTC.EVENT.FIRST_VIDEO_FRAME, ({userId}) => {
    if (userId === m.publisher_user_id) status.textContent = "Video playing";
  });
  await control(s);
  await rtc.enterRoom({sdkAppId: Number(m.sdk_app_id), userId: m.user_id,
    userSig: m.user_sig, strRoomId: m.room_id, scene: TRTC.TYPE.SCENE_RTC, autoReceiveVideo: false});
  window.player = { ws, trtc: rtc };
}
const status = document.querySelector("#status");
const start = document.querySelector("#start");
const stop = document.querySelector("#stop");
let ws, cleanup;
let stopping = false;
async function post(path) {
  const r = await fetch(path, { method: "POST" });
  if (!r.ok) throw new Error(await r.text());
  return path === "/session" ? r.json() : null;
}
async function control(s) {
  const url = new URL(s.control.url);
  url.searchParams.set("token", s.control.client_secret);
  ws = new WebSocket(url);
  await new Promise((resolve, reject) => {
    const timer = setTimeout(() => { ws.close(); reject(new Error("Control timeout")); }, 15000);
    ws.onopen = () => { clearTimeout(timer); resolve(); };
    ws.onerror = ws.onclose = () => { clearTimeout(timer); reject(new Error("Control failed")); };
  });
  ws.onclose = () => { if (!stopping) status.textContent = "Control disconnected. Stop before starting again."; };
  ws.onerror = () => { if (!stopping) status.textContent = "Control error. Click Stop to release the session."; };
}
stop.onclick = async () => {
  stop.disabled = true;
  try { await post("/close"); stopping = true; ws?.close(); await cleanup?.(); cleanup = undefined; delete window.player; status.textContent = "Stopped"; start.disabled = false; }
  catch (e) { status.textContent = `Close failed: ${e.message}. Retry Stop.`; }
  finally { stop.disabled = false; }
};
start.onclick = async () => {
  stopping = false;
  start.disabled = true;
  stop.disabled = true;
  status.textContent = "Starting…";
  try {
    const s = await post("/session");
    status.textContent = "Connected; waiting for video";
    await connect(s);
  } catch (e) {
    status.textContent = `${e.message}. Click Stop to release the session.`;
  } finally { stop.disabled = false; }
};
```

## 2. 构建并启动

```bash theme={null}
npx esbuild main.js --bundle --outfile=app.js
export VIVIX_API_KEY="YOUR_API_KEY"
```

如果已经通过 API 创建会话，请将完整响应保存为 `session-response.json`，然后运行以下命令。点击 Start 后会加入已保存的会话，不会再创建一个：

```bash theme={null}
SESSION_RESPONSE_FILE=./session-response.json node server.mjs
```

如果希望播放器根据 `session.json` 创建新会话，请改为运行：

```bash theme={null}
node server.mjs
```

以上命令二选一。打开 [http://localhost:3000](http://localhost:3000) 并点击 Start。出现视频和 `Video playing` 消息即表示播放成功。点击 Stop 会调用服务端关闭端点，并在本地断开连接。关闭导入的会话后，如果要重新开始，请创建新会话并保存新的响应。

## 3. 常见问题

**创建成功，为什么没有视频？**

检查会话是否仍在运行，以及返回的 `transport` 是否与当前播放器匹配。TRTC 和 Agora 凭证不能互换。加入 RTC 房间并不代表首帧已经到达；示例只有在远端视频开始渲染后才显示 `Video playing`。检查 SDK 错误和 `publisher_user_id` 订阅过滤条件。

**为什么有视频但没有声音？**

浏览器可能阻止自动播放。出现 Enable sound 时点击它，无需创建新会话。该示例只播放远端媒体，不会打开麦克风。

**Stop 失败时应该怎么做？**

如果请求失败，请重试 Stop。返回 `closing` 表示关闭请求已被接受；如需确认最终状态，可以再次查询会话。

接下来可以继续实现[对话](https://docs.vivix.ai/cn/streaming-avatar/interaction/conversation.md)或[外部音频](https://docs.vivix.ai/cn/streaming-avatar/integrate/pure-rendering.md)。服务端清理策略请参阅[会话管理](https://docs.vivix.ai/cn/streaming-avatar/integrate/sessions.md)。

### 用户直接关闭页面时会发生什么？

用户可以直接关闭页面；浏览器会断开媒体和控制连接。如果希望服务端会话随后自动结束，请在 `session.json` 顶层添加 `"auto_close": {"disconnected_timeout_seconds": 60}`。所有控制连接断开 60 秒后，会话开始关闭。需要立即结束时，请使用 Stop。时长规则请参阅[会话管理](https://docs.vivix.ai/cn/streaming-avatar/integrate/sessions.md)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.