1. 准备文件
npm init -y
npm install agora-rtc-sdk-ng
npm install --save-dev esbuild
session.json。
在创建请求中选择 Agora。仅替换前端 SDK 无法将已有的 TRTC 会话转换为 Agora 会话。
{
"delivery": {
"media": {
"transport": "agora"
}
}
}
server.mjs
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
<!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
import AgoraRTC from "agora-rtc-sdk-ng";
async function connect(s) {
const m = s.delivery.media.agora;
if (!m) throw new Error("Expected Agora credentials");
const rtc = AgoraRTC.createClient({mode: "rtc", codec: "vp8"});
const sound = document.querySelector("#sound");
let remoteAudio, remoteVideo;
AgoraRTC.onAutoplayFailed = () => { sound.hidden = false; };
sound.onclick = () => {
sound.hidden = true;
try {
remoteAudio?.play();
remoteVideo?.play("video", {fit: "contain"});
} catch (e) { sound.hidden = false; status.textContent = e.message; }
};
cleanup = async () => {
sound.hidden = true; sound.onclick = null;
AgoraRTC.onAutoplayFailed = undefined;
remoteAudio?.stop(); remoteVideo?.stop();
await rtc.leave(); rtc.removeAllListeners();
};
rtc.on("user-published", async (user, type) => {
if (String(user.uid) !== String(m.publisher_user_id)) return;
try {
await rtc.subscribe(user, type);
if (type === "video") {
remoteVideo = user.videoTrack;
user.videoTrack.on("first-frame-decoded", () => { status.textContent = "Video playing"; });
user.videoTrack.play("video", {fit: "contain"});
}
if (type === "audio") { remoteAudio = user.audioTrack; remoteAudio.play(); }
} catch (e) { status.textContent = e.message; }
});
await control(s);
const text = String(m.user_id);
const uid = /^\d+$/.test(text) && Number.isSafeInteger(Number(text)) ? Number(text) : text;
await rtc.join(m.app_id, m.channel_name, m.token || null, uid);
window.player = { ws, agora: 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. 构建并启动
npx esbuild main.js --bundle --outfile=app.js
export VIVIX_API_KEY="YOUR_API_KEY"
session-response.json,然后运行以下命令。点击 Start 后会加入该会话。快速开始默认创建 TRTC 会话,其响应不能用于当前播放器。
SESSION_RESPONSE_FILE=./session-response.json node server.mjs
session.json 创建新会话,请改为运行:
node server.mjs
Video playing 消息即表示播放成功。点击 Stop 会调用服务端关闭端点,并在本地断开连接。关闭导入的会话后,如果要重新开始,请创建新会话并保存新的响应。
3. 常见问题
创建成功,为什么没有视频? 检查会话是否仍在运行,以及返回的transport 是否与当前播放器匹配。TRTC 和 Agora 凭证不能互换。加入 RTC 房间并不代表首帧已经到达;示例只有在远端视频开始渲染后才显示 Video playing。检查 SDK 错误和 publisher_user_id 订阅过滤条件。
为什么有视频但没有声音?
浏览器可能阻止自动播放。出现 Enable sound 时点击它,无需创建新会话。该示例只播放远端媒体,不会打开麦克风。
Stop 失败时应该怎么做?
如果请求失败,请重试 Stop。返回 closing 表示关闭请求已被接受;如需确认最终状态,可以再次查询会话。
接下来可以继续实现对话或外部音频。服务端清理策略请参阅会话管理。
用户直接关闭页面时会发生什么?
用户可以直接关闭页面;浏览器会断开媒体和控制连接。如果希望服务端会话随后自动结束,请在session.json 顶层添加 "auto_close": {"disconnected_timeout_seconds": 60}。所有控制连接断开 60 秒后,会话开始关闭。需要立即结束时,请使用 Stop。时长规则请参阅会话管理。