modern-winter-66316
12/05/2025, 1:14 AMtall-airline-16756
12/05/2025, 1:14 AMmodern-winter-66316
12/05/2025, 1:14 AMtall-airline-16756
12/05/2025, 1:15 AMautoSubscribe: true should fire TrackSubscribed for tracks published after the client connects, and what to do when the browser sees the agent (active speaker) but never receives TrackSubscribed or audio.
Short answer
• Yes — autoSubscribe: true is intended to subscribe to tracks published after connect and to existing tracks at connect. It should fire TrackSubscribed for the agent's audio.
• Given your symptoms (JS sees active speaker but no TrackSubscribed), this is most likely a timing/registration issue on the client side (race between connect and event handler) or an SDK edge case — not normal autoSubscribe behavior.
What to try (high-impact, minimal changes)
1. Register TrackSubscribed before connect
• Attach your TrackSubscribed handler before calling room.connect(...) so you don’t miss early subscriptions.
room.on(RoomEvent.TrackSubscribed, handleTrackSubscribed);
await room.connect(url, token, { autoSubscribe: true });
1. Post-connect safety check (recover missed tracks)
• After connect, iterate remoteParticipants and their publications and ensure audio publications are subscribed / attached if not already:
for (const p of room.remoteParticipants.values()) {
for (const pub of p.trackPublications.values()) {
if (pub.kind === Track.Kind.Audio && !pub.isSubscribed) {
await pub.setSubscribed(true);
// or call pub.subscription logic / attach publication.track if present
}
}
}
1. Attach or call track.attach() / .play() in your handler
• When TrackSubscribed fires, create/attach the audio element immediately (you mentioned you updated handler to call .play() — keep that).
1. Temporary delay on agent publish (test only)
• For debugging, add a short delay (e.g., 200–500ms) in the agent before publishing audio to confirm it’s a race. If the delay fixes it, client-side listener timing is the root cause.
Other suggestions
• Upgrade JS SDK if possible (v2.16.0 is OK, but later releases include robustness fixes around subscriptions).
• Confirm the agent actually publishes an AudioSource/LocalAudioTrack and RoomOutputOptions audio is enabled (your CLI evidence shows tracks and audio are present, so agent publish looks correct).
If you want, I can provide a small example that:
• Registers listeners before connect,
• Shows a reliable TrackSubscribed handler that attaches audio elements,
• Includes the post-connect check to recover missed audio tracks. Sources: Rooms, participants, and tracks | LiveKit docs | Subscribing to tracks | LiveKit docs | Job lifecycle | LiveKit docsmodern-winter-66316
12/05/2025, 1:16 AMtall-airline-16756
12/05/2025, 1:16 AMimport { Room, RoomEvent, Track } from "livekit-client";
// helper to create/attach audio element and play
function attachAndPlayAudio(track: Track.AudioTrack, trackName?: string) {
const el = track.attach(); // returns HTMLMediaElement
el.autoplay = true;
el.controls = false;
el.dataset.trackName = trackName ?? "";
const container = document.getElementById("audio-container") || document.body;
container.appendChild(el);
// ensure play is attempted (some browsers require user gesture)
const playPromise = (el as HTMLMediaElement).play();
if (playPromise && typeof playPromise.then === "function") {
playPromise.catch((err) => {
console.warn("Audio play prevented by browser autoplay policy:", err);
// UI hint: show a play button for user to enable audio
});
}
}
async function joinRoom(url: string, token: string) {
const room = new Room();
// Register handlers BEFORE connect to avoid missing early events
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
if (track.kind === Track.Kind.Audio) {
console.log("TrackSubscribed:", publication.trackName, participant.identity);
attachAndPlayAudio(track as Track.AudioTrack, publication.trackName);
}
});
room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
// optional: visual indicator
console.log("Active speakers:", speakers.map(s => s.identity));
});
room.on(RoomEvent.ParticipantConnected, (p) => {
console.log("Participant connected:", p.identity);
});
// Connect with autoSubscribe true (default) - still register handlers above first
await room.connect(url, token, { autoSubscribe: true });
// Post-connect safety: ensure any existing audio publications are subscribed/attached
for (const participant of room.remoteParticipants.values()) {
for (const pub of participant.trackPublications.values()) {
if (pub.kind === Track.Kind.Audio) {
// if publication already has a subscribed track, attach it
if (pub.track) {
console.log("Post-connect: attaching already-subscribed track:", pub.trackName, participant.identity);
attachAndPlayAudio(pub.track as Track.AudioTrack, pub.trackName);
} else if (!pub.isSubscribed) {
// explicitly subscribe if not subscribed (recovery path)
try {
console.log("Post-connect: subscribing to audio publication:", pub.trackName, participant.identity);
await pub.setSubscribed(true);
// after subscription, pub.track should be populated and TrackSubscribed will fire
} catch (err) {
console.warn("Failed to subscribe to publication:", err);
}
}
}
}
}
return room;
}
2) Minimal TrackSubscribed handler only (if you already have connect flow)
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
if (track.kind === Track.Kind.Audio) {
attachAndPlayAudio(track as Track.AudioTrack, publication.trackName);
}
});
3) Post-connect manual subscribe loop (standalone)
// run after await room.connect(...)
for (const participant of room.remoteParticipants.values()) {
for (const pub of participant.trackPublications.values()) {
if (pub.kind === Track.Kind.Audio && !pub.isSubscribed) {
try {
await pub.setSubscribed(true);
} catch (err) {
console.warn("subscribe error:", err);
}
// if pub.track exists now, attach it:
if (pub.track) attachAndPlayAudio(pub.track as Track.AudioTrack, pub.trackName);
} else if (pub.kind === Track.Kind.Audio && pub.track) {
attachAndPlayAudio(pub.track as Track.AudioTrack, pub.trackName);
}
}
}
4) Optional: small agent-side delay for testing race condition
• Add a short delay (200–500 ms) in the agent before publishing audio to see if the browser then reliably receives TrackSubscribed. If delay fixes it, client-side event registration timing is the root cause. Remove this delay in production; instead keep the client-side fixes above.
5) Notes / tips
• Autoplay restrictions: browsers often block autoplay of audio without a user gesture. The handler attempts play() and catches rejections; provide a visible play button if autoplay is blocked.
• Attach early: calling track.attach() is appropriate in TrackSubscribed—this creates the HTML element and begins playback when allowed.
• SDK version: upgrading to the latest LiveKit JS SDK can include robustness fixes around subscriptions. Your v2.16.0 is functional, but consider updating if you continue to see missed events.
• Logging: add console logs in TrackSubscribed, ParticipantConnected, and publication loops to trace timing between agent publish and browser events.
If you want, I can convert the above into a runnable single-page example (HTML + JS) that demonstrates joining, subscription, and a simulated agent publish for local testing.modern-winter-66316
12/05/2025, 1:17 AMtall-airline-16756
12/05/2025, 1:17 AM<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>LiveKit Audio Subscribe Example</title>
<script type="module">
import {
Room,
RoomEvent,
Track,
TrackPlaybackQuality,
RemoteTrackPublication,
} from "https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.es.js";
// ====== CONFIGURE ======
const ROOM_URL = "REPLACE_WITH_WS_OR_WS_S_URL"; // e.g. wss://your-livekit.example
const TOKEN = "REPLACE_WITH_TOKEN";
// =======================
const log = (msg, ...args) => {
const el = document.getElementById("log");
const line = document.createElement("div");
line.textContent = `[${new Date().toISOString()}] ${msg}`;
el.prepend(line);
if (args?.length) console.debug(msg, ...args);
};
// helper: attach and attempt play
function attachAndPlayAudio(track, trackName) {
const el = track.attach();
el.autoplay = true;
el.controls = false;
el.dataset.trackName = trackName || "";
const container = document.getElementById("audio-container");
container.appendChild(el);
const playPromise = el.play && el.play();
if (playPromise && typeof playPromise.then === "function") {
playPromise.catch((err) => {
log("Audio play prevented by autoplay policy; showing play button");
document.getElementById("user-play").style.display = "inline-block";
});
}
}
async function run() {
const joinBtn = document.getElementById("join");
const simulateBtn = document.getElementById("simulate-agent");
const playBtn = document.getElementById("user-play");
let room;
joinBtn.onclick = async () => {
joinBtn.disabled = true;
log("Creating room object and registering handlers BEFORE connect");
room = new Room();
// Register relevant handlers BEFORE connect
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
log(`TrackSubscribed: kind=${track.kind} name=${publication.trackName} from=${participant.identity}`);
if (track.kind === Track.Kind.Audio) {
attachAndPlayAudio(track, publication.trackName);
}
});
room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
log("ActiveSpeakersChanged: " + speakers.map(s => s.identity).join(", "));
});
room.on(RoomEvent.ParticipantConnected, (p) => {
log("ParticipantConnected: " + p.identity);
});
room.on(RoomEvent.TrackUnsubscribed, (track, pub, participant) => {
log(`TrackUnsubscribed: ${pub.trackName} from ${participant.identity}`);
});
try {
log("Connecting to room...");
await room.connect(ROOM_URL, TOKEN, { autoSubscribe: true });
log("Connected to room: " + room.name);
// Post-connect safety check: ensure existing audio pubs are subscribed/attached
for (const participant of room.remoteParticipants.values()) {
log(`Checking participant (post-connect): ${participant.identity}`);
for (const pub of participant.trackPublications.values()) {
if (pub.kind === Track.Kind.Audio) {
if (pub.track) {
log(`Post-connect: attaching already-subscribed track ${pub.trackName} from ${participant.identity}`);
attachAndPlayAudio(pub.track, pub.trackName);
} else if (!pub.isSubscribed) {
log(`Post-connect: subscribing to ${pub.trackName} from ${participant.identity}`);
try {
await pub.setSubscribed(true);
// TrackSubscribed should fire after this
} catch (err) {
log("Error subscribing to publication: " + err);
}
}
}
}
}
log("Post-connect safety check complete.");
} catch (err) {
log("Connect error: " + err);
joinBtn.disabled = false;
}
};
// Simulated agent publish for local testing:
// Creates a separate Room and local audio track (microphone) and publishes it.
// Useful to reproduce timing/race issues. This requires user microphone permission.
simulateBtn.onclick = async () => {
simulateBtn.disabled = true;
log("Simulating agent: connecting separate client and publishing mic audio (prompts for mic)");
try {
// For local simulation we use the same TOKEN; in real remote test you'd have a different token for the agent.
const agentRoom = new Room();
agentRoom.on(RoomEvent.ParticipantConnected, (p) => log("AgentRoom ParticipantConnected: " + p.identity));
await agentRoom.connect(ROOM_URL, TOKEN, { autoSubscribe: false });
// get user mic
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
// create a local audio track and publish
const tracks = Array.from(stream.getAudioTracks());
for (const t of tracks) {
// publishLocalTrack not exposed on the browser client in all builds; use room.localParticipant
await agentRoom.localParticipant?.publishTrack(t, { name: "sim-agent-audio" });
log("Agent published mic audio track (simulated)");
}
// Keep agentRoom around for a bit so audio stays published
setTimeout(() => {
log("Simulated agent disconnecting after 30s");
agentRoom.disconnect();
simulateBtn.disabled = false;
}, 30000);
} catch (err) {
log("Simulate agent error: " + err);
simulateBtn.disabled = false;
}
};
// Manual play button if autoplay blocked
playBtn.onclick = () => {
document.querySelectorAll("#audio-container audio, #audio-container video").forEach((el) => {
const media = el;
media.play().catch(err => log("Play click failed: " + err));
});
playBtn.style.display = "none";
};
}
window.addEventListener("load", run);
</script>
<style>
body { font-family: Arial, sans-serif; padding: 12px; }
#controls { margin-bottom: 12px; }
#audio-container audio { display: block; margin-top:8px; }
#user-play { display:none; margin-left:8px; }
#log { max-height: 360px; overflow:auto; border:1px solid #ddd; padding:8px; }
</style>
</head>
<body>
<h3>LiveKit Audio Subscribe Example</h3>
<div id="controls">
<button id="join">Join Room (register handlers before connect)</button>
<button id="simulate-agent">Simulate Agent Publish (use mic)</button>
<button id="user-play">Click to enable audio</button>
</div>
<div id="audio-container"></div>
<div id="log"></div>
</body>
</html>
If you want, I can:
• Swap the simulated agent with an example that uses a server-issued agent token,
• Update the example to use a newer livekit-client CDN version,
• Provide a minimal server snippet to mint tokens for browser vs agent. Which would you like?