Qwen-Audio-Live WebRTC access
Exchange SDP over a control WebSocket to send and receive real-time audio from Qwen-Audio-Live using WebRTC.
Send and receive audio via WebRTC media tracks. Session initialization and SDP negotiation are handled over the control WebSocket, which remains active throughout the session.
Before you begin
Choose the China (Beijing) or Singapore endpoint in WebSocket connection. Use an API key and Workspace ID for the selected region. The browser connects to your application server's WebSocket proxy. The proxy attaches the API key to its connection to Model Studio and forwards JSON events in both directions. Store the API key on the application server. Serve the page over HTTPS or on localhost and allow microphone access.
Connection flow
| Phase | Actions and Checkpoints |
|---|---|
| Open Control Connection | The browser connects to your application server’s proxy; the proxy uses the API Key to connect to Model Studio. |
| Submit Offer SDP | The browser gathers ICE candidates and sends the Offer SDP to session.update over the control WebSocket. |
| Apply Answer SDP | Read the Answer SDP from session.updated’s session.transport.sdp and set it as the remote description. |
| Send and Receive Audio | After the media connection is ready, attach the microphone track. Upon receiving the remote audio track, verify that the player can render speech. |
Generate and send the Offer SDP
Even for voice-only use cases, the Offer SDP must include both m=video and m=application media sections. Adding a video transceiver and creating a DataChannel generate these two media sections respectively. Pure voice integration does not require camera capture or video transmission.
- Create
RTCPeerConnection, add asendrecvaudio transceiver and a video transceiver, then create a DataChannel. In the example, the video transceiver is set torecvonly, and the DataChannel name isoai-events. - Call
createOffer()andsetLocalDescription(). Wait untiliceGatheringStatebecomescomplete, then read the complete Offer SDP—including ICE candidates—fromlocalDescription.sdp. - Send session.update over the control WebSocket. Set
session.transport.typetortcand write the Offer SDP intosession.transport.sdp.
The example uses iceServers: [] to gather local ICE candidates. If your deployment environment requires STUN or TURN, specify the corresponding server configuration in iceServers.
Apply the Answer SDP and start audio
After the server returns session.updated over the control WebSocket, read the Answer SDP from session.transport.sdp. Call setRemoteDescription({ type: "answer", sdp }) to apply the Answer. Once the media connection is established, attach the microphone track and pass the received remote audio track to the player.
Once the media connection is ready, receive server events over the control WebSocket or the WebRTC DataChannel. If both paths deliver an event with the same event_id, handle it once. For example, session.input_transcript.delta and session.output_transcript.delta can arrive on both paths.
Run the browser example
The example uses Responses mode. Install Node.js 20 or later. In an empty directory, run npm install ws and set DASHSCOPE_API_KEY to your Model Studio API key. Copy the WebSocket URL for your region to UPSTREAM_URL in the example and fill in your Workspace ID.
Create the application server
Save the code as server.mjs. The server hosts a local web page and establishes a Model Studio control WebSocket for each browser connection. The example listens only on localhost.
The example includes an optional X-Session-Id header in the upstream WebSocket handshake. Its value starts with sess_ followed by 32 random hexadecimal characters.
import { createServer } from "node:http";
import { randomBytes } from "node:crypto";
import { readFile } from "node:fs/promises";
import WebSocket, { WebSocketServer } from "ws";
const UPSTREAM_URL = "Paste the WebSocket URL with your Workspace ID";
const apiKey = process.env.DASHSCOPE_API_KEY;
const localOrigin = "http://localhost:8000";
if (!apiKey) throw new Error("Set DASHSCOPE_API_KEY");
const files = {
"/": ["index.html", "text/html; charset=utf-8"],
"/live.js": ["live.js", "text/javascript; charset=utf-8"],
};
const server = createServer(async (request, response) => {
const file = Object.hasOwn(files, request.url) && files[request.url];
if (request.method !== "GET" || !file) return response.writeHead(404).end();
try {
const content = await readFile(new URL(file[0], import.meta.url));
response.writeHead(200, { "Content-Type": file[1] }).end(content);
} catch {
response.writeHead(500).end("Check that all example files are present");
}
});
const proxy = new WebSocketServer({ noServer: true });
server.on("upgrade", (request, socket, head) => {
if (request.url !== "/control" || request.headers.origin !== localOrigin) {
socket.destroy();
return;
}
proxy.handleUpgrade(request, socket, head, browser => proxy.emit("connection", browser));
});
proxy.on("connection", browser => {
let upstream;
try {
upstream = new WebSocket(UPSTREAM_URL, {
headers: {
Authorization: `Bearer ${apiKey}`,
"X-Session-Id": `sess_${randomBytes(16).toString("hex")}`,
},
handshakeTimeout: 10000,
});
} catch {
browser.close(1011, "Invalid upstream URL");
return;
}
let closing = false;
function closeBoth() {
if (closing) return;
closing = true;
upstream.terminate();
if (browser.readyState === WebSocket.OPEN) browser.close();
}
browser.on("close", closeBoth);
browser.on("error", closeBoth);
upstream.on("error", () => {
if (!closing && browser.readyState === WebSocket.OPEN) {
browser.close(1011, "Upstream connection failed");
}
closeBoth();
});
upstream.on("close", closeBoth);
browser.on("message", data => {
if (upstream.readyState === WebSocket.OPEN) upstream.send(data.toString());
});
upstream.on("message", data => {
if (browser.readyState === WebSocket.OPEN) browser.send(data.toString());
});
upstream.on("open", () => {
if (browser.readyState === WebSocket.OPEN) {
browser.send(JSON.stringify({ type: "proxy.ready" }));
}
});
});
server.listen(8000, "127.0.0.1", () => console.log(localOrigin));
Create the browser page
Save the following HTML as index.html. Then save the JavaScript below as live.js in the same directory.
<!doctype html>
<html lang="zh-CN">
<meta charset="utf-8">
<title>Qwen-Audio-Live WebRTC example</title>
<button id="start">Start</button>
<button id="end" disabled>End</button>
<audio id="reply" controls></audio>
<p id="status" role="status"></p>
<p>User: <span id="user-text"></span></p>
<p>Model: <span id="model-text"></span></p>
<script src="/live.js" defer></script>
</html>
The browser waits for proxy.ready from the local proxy before initiating SDP negotiation. The application receives subtitles via onTranscript and distinguishes between user and model output using type.
async function startWebRTC(control, audio, onTranscript, onConnected, onError) {
if (control.readyState !== WebSocket.OPEN) throw new Error("Control connection is not open");
let track;
let pc;
let sender;
const channels = [];
const seenTranscripts = new Set();
let answered = false;
let startingAudio = false;
let stopped = false;
let closing = false;
let connectionTimer;
let closeTimer;
function finish() {
if (stopped) return;
stopped = true;
clearTimeout(connectionTimer);
clearTimeout(closeTimer);
track?.stop();
pc?.close();
control.close();
audio.srcObject = null;
seenTranscripts.clear();
}
function fail(error) {
if (stopped) return;
finish();
onError(error);
}
const openChannel = () => channels.find(channel => channel.readyState === "open");
async function startAudio() {
if (stopped || closing || startingAudio || !pc.remoteDescription ||
pc.connectionState !== "connected" || !openChannel()) return;
startingAudio = true;
try {
await sender.replaceTrack(track);
clearTimeout(connectionTimer);
if (!stopped && !closing) {
track.enabled = true;
onConnected();
}
} catch (error) {
fail(error);
}
}
async function receive(raw, fromWebSocket) {
if (stopped) return;
try {
const message = JSON.parse(raw);
if (message.type === "session.updated" && fromWebSocket && !answered) {
const transport = message.session?.transport;
if (transport?.type !== "rtc" || typeof transport.sdp !== "string" || !transport.sdp.trim()) {
throw new Error("No valid Answer SDP in session.updated");
}
answered = true;
const sdp = transport.sdp.trim().replace(/\r?\n/g, "\r\n") + "\r\n";
await pc.setRemoteDescription({ type: "answer", sdp });
await startAudio();
} else if (message.type === "session.input_transcript.delta" ||
message.type === "session.output_transcript.delta") {
const id = message.event_id;
if (id && seenTranscripts.has(id)) return;
if (id) seenTranscripts.add(id);
onTranscript(message);
} else if (message.type === "session.closed" && fromWebSocket) {
finish();
} else if (message.type === "error") {
throw new Error(message.error?.message || "Session failed");
}
} catch (error) {
if (!stopped) fail(error);
}
}
function bindChannel(channel) {
channel.addEventListener("open", startAudio);
channel.addEventListener("message", ({ data }) => receive(data, false));
}
try {
const microphone = await navigator.mediaDevices.getUserMedia({ audio: true });
track = microphone.getAudioTracks()[0];
if (control.readyState !== WebSocket.OPEN) throw new Error("Control connection is closed");
track.enabled = false;
pc = new RTCPeerConnection({ iceServers: [] });
sender = pc.addTransceiver("audio", { direction: "sendrecv" }).sender;
pc.addTransceiver("video", { direction: "recvonly" });
channels.push(pc.createDataChannel("oai-events"));
bindChannel(channels[0]);
pc.addEventListener("datachannel", ({ channel }) => {
channels.push(channel);
bindChannel(channel);
});
pc.addEventListener("track", ({ track: remoteTrack }) => {
if (stopped || remoteTrack.kind !== "audio") return;
audio.srcObject = new MediaStream([remoteTrack]);
audio.play().catch(() => { audio.controls = true; });
});
pc.addEventListener("connectionstatechange", () => {
if (pc.connectionState === "failed") fail(new Error("WebRTC connection failed"));
else void startAudio();
});
control.addEventListener("message", ({ data }) => receive(data, true));
control.addEventListener("close", () => fail(new Error("Control connection closed")));
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve, reject) => {
if (pc.iceGatheringState === "complete") return resolve();
const timer = setTimeout(() => {
pc.removeEventListener("icegatheringstatechange", check);
reject(new Error("ICE candidate gathering timed out"));
}, 15000);
function check() {
if (pc.iceGatheringState !== "complete") return;
clearTimeout(timer);
pc.removeEventListener("icegatheringstatechange", check);
resolve();
}
pc.addEventListener("icegatheringstatechange", check);
});
const sdp = pc.localDescription.sdp;
if (!/^a=candidate:/m.test(sdp)) throw new Error("The Offer is missing ICE candidates");
if (stopped || control.readyState !== WebSocket.OPEN) throw new Error("Control connection is closed");
connectionTimer = setTimeout(() => fail(new Error("WebRTC connection timed out")), 200000);
control.send(JSON.stringify({
type: "session.update",
event_id: crypto.randomUUID(),
session: {
model: "qwen-audio-4.0-realtime-preview",
modalities: ["text", "audio"],
delegation: { type: "responses", responses: { model: "qwen3.8-flash" } },
transport: { type: "rtc", sdp }
}
}));
} catch (error) {
finish();
throw error;
}
return function closeSession() {
if (stopped || closing) return;
closing = true;
clearTimeout(connectionTimer);
track.enabled = false;
try {
control.send(JSON.stringify({ type: "session.close", event_id: crypto.randomUUID() }));
closeTimer = setTimeout(finish, 8000);
} catch (error) {
fail(error);
}
};
}
const startButton = document.querySelector("#start");
const endButton = document.querySelector("#end");
const audio = document.querySelector("#reply");
const statusElement = document.querySelector("#status");
startButton.onclick = () => {
startButton.disabled = true;
statusElement.textContent = "Connecting.";
const control = new WebSocket("ws://localhost:8000/control");
const showError = error => { statusElement.textContent = `Error: ${error.message}`; };
control.addEventListener("error", () => showError(new Error("Could not connect to the local proxy")));
control.addEventListener("close", event => {
endButton.disabled = true;
if (event.reason) showError(new Error(event.reason));
if (!statusElement.textContent.startsWith("Error:")) statusElement.textContent = "Connection closed.";
});
control.addEventListener("message", async function waitForProxy({ data }) {
if (JSON.parse(data).type !== "proxy.ready") return;
control.removeEventListener("message", waitForProxy);
try {
const closeSession = await startWebRTC(control, audio, event => {
const selector = event.type === "session.input_transcript.delta" ? "#user-text" : "#model-text";
document.querySelector(selector).textContent += event.delta;
}, () => { statusElement.textContent = "Media connected. You can speak now."; }, showError);
endButton.disabled = false;
endButton.onclick = closeSession;
} catch (error) {
showError(error);
}
});
};
Verify the connection
Run node server.mjs, open http://localhost:8000, and click Start and allow microphone access. After the page displays "Media connected. You can speak now.", say a sentence and confirm that the player outputs the model’s voice reply. To start a new session, refresh the page. If subtitles appear but no audio plays, verify whether the track callback received the remote audio track, then check whether the browser blocked autoplay. If no Answer is received, first confirm that the Offer includes m=video and m=application, then inspect server-side errors. If an Answer is received but the media connection fails to establish, verify whether the Answer has been applied and whether the Offer contains ICE candidates usable on the current network.
Handle tasks and end the session
For business integration, see Choose a delegation mode. Request and response fields are documented in Client Events and Server Events.
Click End; the example invokes closeSession() to send session.close. Upon receiving session.closed, stop audio capture and close the connection.