cant hear agent
# ask-ai
m
cant hear agent
t
Thanks for reaching out, aigentzi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
m
Problem: Browser client (LiveKit JS SDK) does not receive TrackSubscribed events for agent audio tracks, even though the agent successfully joins the room and publishes audio. Evidence: 1. Debug CLI client (Python livekit library): ◦ Successfully sees trackPublished roomio_audio agent-AJ_... ◦ Successfully sees trackSubscribed audio agent-AJ_... ◦ Can hear agent audio. 2. Web browser client (LiveKit JS SDK v2.16.0): ◦ Connects to room successfully. ◦ Sees agent as "active speaker" via ActiveSpeakersChanged event. ◦ Does NOT receive TrackSubscribed event for agent's audio track. ◦ Audio element never created → no sound. Configuration: • Room creation: Uses RoomServiceClient.createRoom() with emptyTimeout: 300, maxParticipants: 2. • Agent dispatch: Uses AccessToken.roomConfig.agents for on-join dispatch (token-based dispatch). • Browser connection: room.connect(url, token, { autoSubscribe: true }). • Agent: LiveKit Cloud Python agent, deployed via lk agent deploy, publishes audio via AgentSession with LiveKit Inference (STT/LLM/TTS model strings only). Timeline: • Agent joins after browser user joins (dispatched on-join). • Agent publishes audio track ~1-2 seconds after connecting. • Browser's TrackSubscribed event never fires for that track. Possible causes: 1. autoSubscribe: true may not work when tracks are published after the client connects. 2. Race condition: agent publishes track before browser's event handlers are fully registered. 3. Browser client may need to manually enumerate room.remoteParticipants and subscribe to existing tracks after connect(). Workaround attempted: Added manual subscription loop after room.connect(): js Question for LiveKit: Is autoSubscribe: true guaranteed to fire TrackSubscribed for tracks published after the client connects, or do we need to manually handle late-joining participants' tracks? What changed recently (that may have broken it): If this was working perfectly before, the only changes in this session were: 1. Agent code: added persona logic (personas.py, get_persona()) — this caused a crash initially (fixed by redeploying agent). 2. Browser code: updated TrackSubscribed handler to explicitly call .play() and log events. Neither of these should have broken autoSubscribe behavior. The most likely explanation is that the agent now joins and publishes audio slightly faster (after fixing the crash), and the browser's autoSubscribe isn't catching it in time. Let me know what LiveKit support says, and I can adjust the workaround accordingly.
t
Thanks — I looked over your info. You're asking whether
autoSubscribe: 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.
Copy code
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:
Copy code
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 docs
m
please give me all of those thanks
t
Below is a complete, copy-paste-ready solution that implements all recommended fixes: register listeners before connecting, a robust TrackSubscribed handler that attaches audio elements and plays them, and a post-connect safety check that subscribes/attaches any missed audio tracks. It also includes an optional small delay suggestion for the agent (for testing). All snippets are for LiveKit JS SDK (v2.x). 1) Full browser example (register before connect + TrackSubscribed handler + post-connect safety check)
Copy code
import { 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)
Copy code
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)
Copy code
// 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.
m
yes pls
t
Below is a single-file HTML + JS example you can copy-paste and run locally. It demonstrates: • Registering event handlers before connect • Robust TrackSubscribed handler that attaches and attempts play • Post-connect safety loop to subscribe/attach missed audio tracks • Logging to help trace timing • A simulated "agent publish" button for local testing (it simulates a remote participant by creating a second Room instance — useful for debugging race conditions) Notes: • Replace ROOM_URL and TOKEN with your server values. • Browser autoplay may block playback; the example shows a play button if autoplay fails.
Copy code
<!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?