in which format livekit agent sends the rtc audio ...
# ask-ai
m
in which format livekit agent sends the rtc audio frames to the client?
t
Thanks for reaching out, Alexey. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Regarding the format of RTC audio frames sent by the LiveKit agent to the client: LiveKit sends the audio as raw PCM in
pcm_s16le
(signed 16-bit little-endian) with the sample rate matching the incoming stream (typically 48 kHz). Text/json frames may also be sent for track state changes (e.g., mute/unmute). Would you like details on handling these frames on the client (parsing/playback or piping to a transcription service)? Sources: Track egress | LiveKit docs | Universal Egress
m
yes
t
Great — I’ll explain how to handle, parse, and play LiveKit’s audio frames on the client, and how to pipe them to a transcription service. Acknowledgement • You asked for details on parsing/playback and sending audio to transcription after confirming LiveKit sends audio as raw PCM
pcm_s16le
(48 kHz, 16-bit mono). What you can do (options) • Playback (normal use): Let the SDK handle decoding and playback; in web use
track.attach()
to connect the audio track to an HTMLAudioElement. • Access raw PCM frames for processing/transcription: Use the SDK’s audio-frame streaming API to read
AudioFrame
objects whose
data
field contains
pcm_s16le
bytes. • Export via TrackEgress to WebSocket: Configure TrackEgress to stream
pcm_s16le
binary frames to a WebSocket server, where you can forward them to a transcription engine. Quick examples and next steps 1) Web playback (JS) • Subscribe and attach:
Copy code
participant.on('trackSubscribed', (track) => {
  if (track.kind === 'audio') {
    const audioEl = track.attach();
    document.body.appendChild(audioEl);
  }
});
2) Read raw PCM frames (pseudo/SDK pattern) • Use the client API to consume audio frames and access
frame.data
(raw
pcm_s16le
bytes). Then: ◦ Convert to the format your transcription API expects (many accept 16-bit PCM little-endian at 16/32 kHz or 48 kHz). ◦ If needed, resample to the transcription service sample rate (e.g., 16 kHz) before sending. 3) TrackEgress → WebSocket → Transcription • Configure TrackEgress to send binary
pcm_s16le
frames to your WebSocket endpoint. • On the WebSocket server, receive binary frames and forward them (possibly after resampling) to the transcription service’s streaming API. Notes and best practices • Sample rate: LiveKit uses the incoming stream’s sample rate (typically 48 kHz). Resample when a transcription service requires a different rate. • Channel/bit depth: Frames are 16-bit PCM, mono by default. • Text frames: Expect occasional JSON/text frames for track state (mute/unmute); skip or handle them separately from binary audio frames. • Volume control and playback sync: Use SDK volume APIs for per-track volume. WebRTC handles jitter and sync; only implement buffering/resampling if you do custom processing. • Latency: For lowest latency, stream raw PCM to the transcriber with minimal buffering and avoid extra encoding steps. Would you like: • an example showing resampling PCM to 16 kHz in Node/Python, or • a WebSocket server snippet that forwards pcm_s16le frames to a specific transcription API? Sources: Track egress | LiveKit docs | Subscribing to tracks | LiveKit docs | Camera & microphone | LiveKit docs | Stream music over WebRTC using React and WebAudio | Bringing Zoom's end-to-end optimizations to WebRTC
m
how to proceed it in python backend and send to frontend for the playback? show me backend paython and frontend typescript examples.
t
Below are concise, working-pattern examples showing how to: (1) receive raw PCM audio frames in a Python LiveKit Agent, publish a processed audio track back into the room, and (2) subscribe/play that processed track in a TypeScript frontend. These follow the LiveKit SDK patterns: use
rtc.AudioStream
to read frames,
rtc.AudioSource.capture_frame()
to publish processed frames, and
track.attach()
on the client for playback. Backend — Python (LiveKit Agent) • Behavior: subscribe to incoming audio tracks, read
pcm_s16le
bytes from
frame.data
, optionally process (example: simple passthrough or gain), publish processed audio via a
LocalAudioTrack
.
Copy code
# backend_agent.py
import asyncio
import numpy as np
from livekit import rtc
from livekit.agents import JobContext, WorkerOptions, cli

# global audio source so we can publish one processed track
_audio_source = None

async def process_audio(track: rtc.RemoteAudioTrack):
    global _audio_source

    stream = rtc.AudioStream(track)
    async for frame_event in stream:
        frame = frame_event.frame
        raw_pcm: bytes = frame.data                 # pcm_s16le bytes
        sample_rate = frame.sample_rate             # typically 48000
        num_channels = frame.num_channels           # typically 1
        samples_per_channel = frame.samples_per_channel

        # --- Processing example: apply gain (1.2) ---
        pcm_arr = np.frombuffer(raw_pcm, dtype=np.int16)
        pcm_arr = (pcm_arr.astype(np.float32) * 1.2).clip(-32768, 32767).astype(np.int16)
        processed_bytes = pcm_arr.tobytes()

        # Create AudioFrame and send to source
        await _audio_source.capture_frame(
            rtc.AudioFrame(
                data=processed_bytes,
                sample_rate=sample_rate,
                num_channels=num_channels,
                samples_per_channel=samples_per_channel,
            )
        )

async def room_entrypoint(ctx: JobContext):
    global _audio_source
    room = ctx.room

    # create an audio source and publish a processed audio track
    _audio_source = rtc.AudioSource(48000, 1)  # sample rate & channels (adjust if needed)
    processed_track = rtc.LocalAudioTrack.create_audio_track("processed-audio", _audio_source)
    await room.local_participant.publish_track(processed_track)

    # handle new subscriptions
    @room.on("track_subscribed")
    def on_track_subscribed(track: rtc.Track, *_):
        if track.kind == rtc.TrackKind.KIND_AUDIO:
            # spawn background task per audio track
            asyncio.create_task(process_audio(track))

    # process tracks already present
    for participant in room.remote_participants.values():
        for tp in participant.track_publications.values():
            if tp.kind == rtc.TrackKind.KIND_AUDIO and tp.track:
                asyncio.create_task(process_audio(tp.track))

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=room_entrypoint))
Notes (backend): • Frames read via
rtc.AudioStream
contain
pcm_s16le
in
frame.data
. • Use numpy/scipy for DSP or resampling if transcription requires different sample rate. • Keep processing low-latency; avoid large buffers for real-time playback. • Ensure agent has publish permission in the room. Frontend — TypeScript (LiveKit client) • Behavior: connect to LiveKit room, subscribe to tracks, attach audio elements for playback. The processed audio track name used above is "processed-audio".
Copy code
// frontend.ts
import { Room, RoomEvent, Track } from "livekit-client";

async function start() {
  const room = new Room();

  // connect: replace with your LiveKit URL and token
  await room.connect("wss://your-livekit-server", "YOUR_ACCESS_TOKEN");

  // play existing and future audio tracks
  const attachAudio = (track: Track) => {
    // track.attach() creates an HTMLAudioElement that auto-plays the subscribed audio
    const audioEl = track.attach();
    audioEl.autoplay = true;
    audioEl.controls = true;
    document.body.appendChild(audioEl);
  };

  // attach already subscribed tracks (on join)
  room.localParticipant.tracks.forEach((pub) => {
    const t = pub.track;
    if (t && t.kind === Track.Kind.Audio) attachAudio(t);
  });

  // attach new tracks as they subscribe
  room.on(RoomEvent.TrackSubscribed, (track) => {
    if (track.kind === Track.Kind.Audio) {
      // optionally filter by track name:
      // if ((track as any).name === "processed-audio") { ... }
      attachAudio(track);
    }
  });

  // optional: handle trackUnsubscribed to remove elements
  room.on(RoomEvent.TrackUnsubscribed, (track) => {
    const els = track.detach();
    els.forEach((el) => el.remove());
  });
}

start().catch(console.error);
Frontend notes: •
track.attach()
handles playback; browser decodes WebRTC audio (no extra decoding required). • If you published processed audio as mono 48 kHz, the browser playback will handle it. • For custom WebAudio processing in the browser, route the MediaStream to a
MediaStreamAudioSourceNode
. If you want, I can: • Add a Node/Python snippet to resample
pcm_s16le
from 48 kHz → 16 kHz (common for transcription) before forwarding to a transcription API. • Provide a WebSocket alternative (backend sends pcm frames over WS and frontend plays via WebAudio) if you prefer not to republish into the LiveKit room. Which would you like? Sources: Job lifecycle | LiveKit docs | Camera & microphone | LiveKit docs | Processing raw media tracks | LiveKit docs | Subscribing to tracks | LiveKit docs | Capturing the First Few Seconds of a Call for Processing
m
how to check if the
processed_bytes
have the valid values?
t
Regarding verifying
processed_bytes
(raw
pcm_s16le
) — here are practical checks and quick diagnostics you can run in your Python backend to ensure the data is valid before sending/publishing. 1) Basic structural checks • Non-empty:
Copy code
if not processed_bytes:
    raise ValueError("empty audio payload")
• Length aligned to 16-bit samples:
Copy code
if len(processed_bytes) % 2 != 0:
    raise ValueError("byte length not multiple of 2")
2) Interpret as int16 and check dtype/shape
Copy code
import numpy as np
pcm = np.frombuffer(processed_bytes, dtype=np.int16)
# ensure got samples
if pcm.size == 0:
    raise ValueError("no samples after decode")
3) Value-range checks (no clipping/artifacts) • Expected range for int16: [-32768, 32767]
Copy code
if pcm.min() < -32768 or pcm.max() > 32767:
    raise ValueError("sample values out of int16 range")
• Detect heavy clipping (many samples at max/min):
Copy code
clip_ratio = np.mean((pcm == 32767) | (pcm == -32768))
if clip_ratio > 0.001:  # tune threshold
    print("warning: possible clipping, clip_ratio=", clip_ratio)
4) DC offset / silence checks
Copy code
mean = pcm.mean()
rms = np.sqrt(np.mean(pcm.astype(np.float32)**2))
if abs(mean) > 1000:
    print("warning: large DC offset:", mean)
if rms < 100:  # near-silence threshold; tune as needed
    print("warning: very low level (silence) rms=", rms)
5) Short-term statistics / spectrum check (detect noise or flatlines)
Copy code
# short-time energy variance
window = pcm[:4800]  # first 0.1s at 48kHz
energy = np.mean(window.astype(np.float32)**2)
# quick FFT to see frequency content
spec = np.abs(np.fft.rfft(window.astype(np.float32)))
if spec.sum() == 0:
    print("warning: no spectral energy")
6) Timestamp / frame-size consistency • If you expect N samples per frame (e.g., 480 samples @10ms for 48kHz), confirm:
Copy code
expected_samples = 480  # example
if pcm.size % expected_samples != 0:
    print("warning: unexpected frame length:", pcm.size)
7) Quick listen or write-to-WAV for manual inspection
Copy code
import wave
with wave.open("debug.wav", "wb") as wf:
    wf.setnchannels(1)
    wf.setsampwidth(2)
    wf.setframerate(48000)
    wf.writeframes(processed_bytes)
# then play debug.wav locally
8) Defensive checks before capture_frame / publish • Ensure sample_rate, num_channels, and samples_per_channel you send match the frame metadata. • Wrap publish in try/except and log failing frames with their stats. If you want, I can provide: • a small utility function that performs these checks and returns a report, or • a ready-to-run snippet that logs/alerts on common problems (clipping, DC offset, silence, wrong frame size). Which would you prefer?
m
why do you apply gain 1.2?
t
Good question — the 1.2 gain in the example was purely illustrative, not a requirement. Why it was used • It shows how to modify samples (a simple gain example) so you can see processing in-place. • It demonstrates converting bytes → numeric array, applying an operation, clipping to int16 bounds, and converting back. When to change it • Use >1.0 to increase loudness, <1.0 to reduce. • Avoid large gains that cause clipping; always clip to [-32768, 32767]. • Choose gain based on measured RMS/target level, not arbitrarily. Better approaches • Automatic Gain Control (AGC): compute RMS and adjust gain to reach a target RMS. • Normalize per-frame: scale by target_peak / current_peak (with smoothing) to avoid sudden jumps. • Limit/Compressor: apply a limiter or compressor to prevent clipping while raising perceived loudness. If you want, I can: • provide a ready Python snippet that applies AGC (RMS-based) with smoothing, or • show a conservative gain example with clipping detection and logging. Which do you prefer?
m
i see my agent sends the correct audio frames, but in the python backend i get the silence:
Copy code
pcm_arr = np.frombuffer(frame.data, dtype=np.int16) 
// --> Audio frame stats: samples=4410, min=-2, max=1, avg_abs=0.02 - {}
what could be the reason?
t
Thanks — I’m responding to your observation that frames arrive but look like silence (samples small around -2..1, avg_abs 0.02). Below are the most likely causes and concrete checks to narrow it down. Immediate checks (run these first) 1. Confirm track identity • Log participant.identity and track.name when you start processing to ensure you’re reading the intended track (not a different participant or data track). 1. Muted / DTX / silence on sender • Verify the publisher isn’t muted. DTX (silence suppression) can produce near-zero samples during silence; check the publisher side for mute/state changes. • On the sender, confirm audio capture is sending non-silent audio (record a local debug WAV on the sending client and play it). 1. Verify sample alignment / endianness • Ensure you interpret bytes as little-endian int16 (
np.int16
is fine on little-endian hosts). Check: ◦ print(frame.sample_rate, frame.num_channels, len(frame.data)) ◦ confirm len(frame.data) == samples_per_channel * num_channels * 2 1. Check for scaling/normalization bug • If earlier code modified or normalized frames, ensure you aren’t dividing by a large factor or unintentionally converting to float and then truncating to small ints. • Inspect raw bytes hex for non-zero data:
Copy code
print(frame.data[:32].hex())
1. Stereo/Channel mapping mismatch • If incoming is stereo but you treat as mono, you may be reading half the meaningful samples. Check
num_channels
and interpret accordingly:
Copy code
pcm = np.frombuffer(frame.data, dtype=np.int16).reshape(-1, num_channels)
1. Resampling/processing pipeline issue • If you resample or use libraries that expect float32 in [-1,1], confirm conversions are correct: ◦ int16 -> float32: pcm_f = pcm_int16.astype(np.float32) / 32768.0 ◦ float32 -> int16: pcm_int16 = (pcm_f * 32767.0).astype(np.int16) 1. Frame duration vs expectation • Your stats show samples=4410 — that looks like 100ms @44.1kHz (or 92.7ms @48kHz). Confirm
frame.sample_rate
and expected samples_per_channel; mismatch can cause mis-read frames. Diagnostics to run now (paste results if you want me to interpret) • Print metadata and quick stats:
Copy code
pcm = np.frombuffer(frame.data, dtype=np.int16)
print("meta:", frame.sample_rate, frame.num_channels, len(frame.data), "samples:", pcm.size)
print("stats:", pcm.min(), pcm.max(), pcm.mean(), np.mean(np.abs(pcm)))
print("first32 hex:", frame.data[:64].hex())
• If
num_channels > 1
, run:
Copy code
pcm = pcm.reshape(-1, frame.num_channels)
print("ch0 stats:", np.mean(np.abs(pcm[:,0])), "ch1 stats:", np.mean(np.abs(pcm[:,1])))
Other possible causes • Sender audio level is extremely low (microphone gain/AGC issue). • A-level processing on agent (e.g., intentional silence injection or voice activity detection). • Your backend is reading a track after it has been muted/paused (subscribe timing). Next steps I can help with • Interpret the diagnostic output above. • Provide a snippet to correctly reshape multi-channel frames, convert to float, and write a WAV for manual listening. • Help add logging on the sender/agent to confirm non-silent data before it reaches the backend. Which diagnostic output can you share now?
m
how can i check if my agent is not muted, when connected to room?
t
Responding to how to check if your agent is muted when connected to a room — here are concise, actionable methods you can run from the agent/backend. 1) Inspect TrackPublication.muted via room events (agent-side) • Listen for publication and mute/unmute events and log the publication state.
Copy code
@room.on("track_published")
def on_track_published(publication, participant):
    print("published:", publication.sid, "muted:", publication.muted, "by", participant.identity)

@room.on("track_muted")
def on_track_muted(publication, participant):
    print("muted:", publication.sid, "by", participant.identity)

@room.on("track_unmuted")
def on_track_unmuted(publication, participant):
    print("unmuted:", publication.sid, "by", participant.identity)
2) Check the local track publication (if agent published the audio) • After publishing, inspect the returned publication object:
Copy code
pub = await room.local_participant.publish_track(local_audio_track)
print("local publish muted:", pub.muted)
# to unmute if needed
await pub.unmute()
3) Query participant state server-side (RoomService / REST API) • Use the RoomService/GetParticipant API to fetch participant details and check each track’s
muted
field (requires room-admin credentials).
Copy code
participant = await lkapi.room.get_participant(room=room_name, identity=agent_identity)
for t in participant.tracks:
    print(t.sid, t.kind, "muted=", t.muted)
4) Quick runtime checks to confirm non-silent publishing • Ensure the agent is actually sending non-zero samples before publish:
Copy code
pcm = np.frombuffer(frame.data, dtype=np.int16)
print("agent frame stats:", pcm.size, pcm.min(), pcm.max(), np.mean(np.abs(pcm)))
• If values are near zero, check sender mute/DTX/voice-activity settings on the publisher side. Which of these would you like a full snippet for (RoomService call, event wiring, or publishing/unmuting example)? Sources: Managing participants | LiveKit docs | livekit/livekit_composite | DeepWiki | Subscribing to tracks | LiveKit docs | Camera & microphone | LiveKit docs
m
i send the base64 encoded pcm16 buffer to the frontend. how to proceed and play single audio frame in the frontend?
t
You can decode the base64 PCM16 frame, convert samples to Float32 [-1,1], create an AudioBuffer and play it via the Web Audio API. Below is a minimal TypeScript example that plays one received base64
pcm_s16le
frame (mono, 48000 Hz). It also shows how to append multiple frames to a single AudioBufferSourceNode for near-real-time playback. Frontend TypeScript — play single PCM16 frame
Copy code
// decode base64 -> Int16Array
function base64ToInt16(base64: string): Int16Array {
  const binary = atob(base64);
  const len = binary.length;
  const buf = new ArrayBuffer(len);
  const view = new Uint8Array(buf);
  for (let i = 0; i < len; i++) view[i] = binary.charCodeAt(i);
  return new Int16Array(buf);
}

// convert Int16Array -> Float32Array in range [-1, 1]
function int16ToFloat32(int16: Int16Array): Float32Array {
  const f32 = new Float32Array(int16.length);
  for (let i = 0; i < int16.length; i++) {
    f32[i] = Math.max(-1, int16[i] / 32768);
  }
  return f32;
}

// play a single mono frame
async function playPcmFrame(base64: string, sampleRate = 48000) {
  const int16 = base64ToInt16(base64);
  const float32 = int16ToFloat32(int16);

  const ac = new (window.AudioContext || (window as any).webkitAudioContext)();
  // create buffer: 1 channel, length = number of samples, sampleRate
  const audioBuffer = ac.createBuffer(1, float32.length, sampleRate);
  audioBuffer.getChannelData(0).set(float32);

  const src = ac.createBufferSource();
  src.buffer = audioBuffer;
  src.connect(ac.destination);
  src.start();
  // optional: stop and close after playback
  src.onended = () => { ac.close(); };
}
Notes and tips • Endianness:
pcm_s16le
is little-endian. The above assumes the base64 was created from native little-endian bytes. If bytes were swapped, decode accordingly. • Channels: If data is stereo, reshape and copy each channel into separate channel arrays: ◦ Example: interleaved int16 -> split to left/right Float32 arrays before creating a 2-channel AudioBuffer. • Latency / streaming: Creating a new AudioContext and BufferSource per frame is fine for short debugging but inefficient for continuous streaming. ◦ For streaming, create one persistent AudioContext and a ScriptProcessor/AudioWorklet or use a queue to append frames to a SourceBuffer pattern: ▪︎ Use an AudioWorklet or an OfflineAudioContext pattern to feed continuous frames into the audio graph with minimal gap. • Smooth playback: pad or overlap frames or use a small FIFO buffer to avoid gaps between frames. Align playback timestamps using AudioContext.currentTime + offset when scheduling
start()
. If you want, I can provide: • a stereo example (interleaved samples), • a streaming example using an AudioWorklet with a sample FIFO, or • a Node/WS example showing how to send the base64 frames from backend to frontend. Which one would help most?
m
can two standalone workers (STT and TTS) both connect to the same room at the same time?
t
Yes — two (or more) standalone workers (e.g., an STT worker and a TTS worker) can connect to the same LiveKit room simultaneously. Key points and best practices: • Each worker connects as its own participant with a unique identity and its own access token. • Workers can independently publish and subscribe to tracks (STT subscribes to user audio, TTS publishes audio output). • Ensure tokens grant the correct permissions (publish vs subscribe) for each worker. • Distinguish workers by identity or track names so you can route audio/logic correctly. • Keep processing latency low and avoid blocking the audio pipeline; publish processed audio back into the room (or use a WebSocket egress) depending on your architecture. If you’d like, I can provide sample connection code for both workers (Python agent for STT subscription and TTS publisher, plus how to identify their tracks in the room). Which sample do you want first? Sources: Rooms, participants, and tracks | LiveKit docs | Connecting to LiveKit | LiveKit docs | An open source stack for real-time multimodal AI | Agent server | LiveKit docs | Authentication | LiveKit docs
m
i create a tts stream with tts.stream(), then push text to it and then call tts.end_input(). how to open it again to push text?
t
You cannot reopen a TTS stream after calling
end_input()
— that call finalizes and closes the stream. To send more text, create a new stream with
tts.stream()
and push text to that new stream. Example pattern:
Copy code
# first utterance
s1 = tts.stream()
s1.push_text("Hello")
s1.end_input()

# additional utterance → new stream
s2 = tts.stream()
s2.push_text("Another message")
s2.end_input()
Best practice: create a fresh stream per logical utterance or response. If you need continuous multi-part input, accumulate text client-side and send in one stream, or create/publish multiple streams as separate utterances. Sources: Text-to-speech (TTS) models | LiveKit Docs
m
in this example:
Copy code
# push text into the stream, TTS stream will emit audio frames along with events
    # indicating sentence (or segment) boundaries.
    async for text in text_stream:
        tts_stream.push_text(text)
    tts_stream.end_input()
how to create event, indicating sentence?
t
You don't manually create sentence-boundary events — the TTS stream emits them during synthesis. To detect those events, read the synthesized-audio stream and watch the metadata that marks segment/sentence completion (e.g.,
text_index
,
text
, or a segment/completed flag). Example (Python) — listen for segment events while pushing text:
Copy code
tts_stream = tts.stream()

# consumer: async iterate synthesized audio events produced by the stream
async def consume():
    async for synth in tts_stream.synthesized_audio():
        # synth contains audio.frame plus metadata
        # common fields: synth.text, synth.text_index, synth.is_final (or similar)
        print("synth event:", synth.text_index, synth.text)
        # detect boundary: example when text_index increments or is_final True
        if getattr(synth, "is_final", False) or synth.text_index >= 0:
            print("segment/sentence boundary:", synth.text)
        # capture/play audio frame
        await audio_source.capture_frame(synth.audio.frame)

# producer: push text (push full sentences for clear boundaries)
async def produce(text_stream):
    async for text in text_stream:
        tts_stream.push_text(text)
    tts_stream.end_input()

# run concurrently
await asyncio.gather(produce(my_text_stream), consume())
Tips to control segmentation • Push complete sentences or meaningful chunks (not word-by-word) so emitted segments align with sentences. • Use SSML (e.g.,
<s>...</s>
,
<break time="200ms"/>
) if the TTS provider supports it to force pauses/boundaries. • If you need explicit, app-level events, emit them yourself when you call
push_text()
for a sentence (e.g., send a "sentence_started"/"sentence_queued" event alongside push), and correlate with synth events when
synth.text
or
text_index
appears. If you share the TTS stream event objects you see (fields like
text_index
,
text
,
is_final
, or the audio event shape), I can give an exact detection condition and a short snippet tailored to that shape. Sources: Text-to-speech (TTS) models | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Amazon Polly TTS plugin guide | LiveKit Docs
m
if i push 10 sentences one after another and then end_input(). will be the audio generated only after i’ve send end_input() or immediately after the first sentence?
t
Audio is generated progressively as you push sentences — you don’t need to call
end_input()
to get audio for earlier sentences. Pushing text causes the TTS stream to synthesize and emit audio frames (and segment events) as segments are produced. Calling
end_input()
only signals there’s no more text and causes finalization of any remaining buffered input. Best practice: push complete sentences (or include SSML breaks) so segmentation aligns with sentence boundaries; call
end_input()
when you’re done sending all parts.
m
how to use it if my text stream generated by @ctx.room.on(“data_received”) event?
t
You can push text into a TTS stream from the
@ctx.room.on("data_received")
event as data arrives — handle events by forwarding received text into the open TTS stream, and call
end_input()
only when you know no more text will arrive for that utterance. Below is a minimal pattern showing safe, real-time usage plus an optional batching approach. 1) Real-time: push each received message immediately
Copy code
# create stream once for this logical utterance
tts_stream = tts.stream()

@ctx.room.on("data_received")
def on_data_received(payload, participant):
    # extract text from payload (depends on your app)
    text = payload.get("text")
    if not text:
        return
    # push text as it arrives
    tts_stream.push_text(text)

# when you decide the utterance is complete:
tts_stream.end_input()
2) Concurrency with synth consumer (consume synthesized audio while pushing)
Copy code
async def consume_synth():
    async for synth in tts_stream.synthesized_audio():
        # handle emitted audio frames/segment metadata
        await audio_source.capture_frame(synth.audio.frame)

# run consumer in background
import asyncio
asyncio.create_task(consume_synth())
3) Batch / sentence accumulation (if you need sentence boundaries) • Buffer incoming chunks and push only when you detect a sentence end (e.g., punctuation or an explicit "end" data message).
Copy code
buffer = []

@ctx.room.on("data_received")
def on_data_received(payload, _):
    text = payload.get("text")
    if not text:
        return
    buffer.append(text)
    # if payload signals end_of_sentence or text ends with punctuation:
    if text.strip().endswith((".", "?", "!")) or payload.get("end_sentence"):
        tts_stream.push_text(" ".join(buffer))
        buffer.clear()

# when all input done:
tts_stream.end_input()
Notes and best practices • A single TTS stream is one logical utterance; create a new stream for separate utterances after calling
end_input()
. • If data_received can be high-frequency, push full sentences or use batching to avoid excessive small segments. • Use SSML in pushed text if you need explicit pauses/breaks. • Run the synth consumer concurrently so audio plays as segments are produced (no need to wait for end_input()). If you share the shape of your
data_received
payload (how text and end-of-sentence are indicated), I can provide a tailored snippet that handles those fields. Would you like that?
m
should i make tts_stream.aclose() and ctx.shutdown() after the complete text was pushed?
t
Yes — call both, but at different times: • Call
tts_stream.end_input()
when you’ve sent the final text for that utterance. • Then call
await tts_stream.aclose()
to finalize synthesis and free stream resources (do this after you’ve consumed remaining synthesized audio). • Only call
await ctx.shutdown()
when your agent/job is finished and you want to disconnect the agent from the room entirely. Example pattern:
Copy code
# push inputs
tts_stream.push_text("Hello.")
tts_stream.push_text("How are you?")
tts_stream.end_input()

# consume remaining audio (concurrently) then close stream
await tts_stream.aclose()

# continue other work OR when done with the agent:
await ctx.shutdown()
Don’t call
ctx.shutdown()
after every TTS utterance unless you intend to stop the agent. Sources: Job lifecycle | LiveKit docs
m
when i closed tts stream with aclose(), should i make asyncio.create_task(…) again, when the next poece of text comes and the audio must be generated?
t
After you call
await tts_stream.aclose()
, that stream is finished and cannot be reused. For the next piece of text you should: • create a new stream with
tts.stream()
• start a new consumer task (e.g., via
asyncio.create_task(...)
) to consume the new stream’s synthesized-audio events and publish/capture frames • push text to the new stream, call
end_input()
, await
aclose()
when done Minimal pattern:
Copy code
async def handle_utterance(text_chunks):
    tts_stream = tts.stream()

    async def consume():
        async for synth in tts_stream.synthesized_audio():
            await audio_source.capture_frame(synth.audio.frame)
    task = asyncio.create_task(consume())

    for chunk in text_chunks:
        tts_stream.push_text(chunk)
    tts_stream.end_input()
    await tts_stream.aclose()
    await task  # wait for consumer to finish
Best practices: • Create one stream + one consumer task per logical utterance/response. • Reuse long-lived resources (audio source, ctx) but recreate streams/tasks per utterance. • If you expect frequent short utterances, keep the consumer logic lightweight and avoid blocking calls inside it. Would you like a version that batches incoming data_received events into sentences before creating streams?
m
Copy code
# consumer
audio_stream = rtc.AudioStream.from_track(...)

async def handle_audio_stream(self, track: rtc.Track)
    async for audio_event in audio_stream:
        frame = audio_event.frame  # rtc.AudioFrame
        ...

asyncio.create_task(self.handle_audio_stream(track))
how can i recognize the end of the generated audio stream in audio_event?
t
You detect the end of the audio stream by the async iterator finishing — there is no end-of-stream flag on
audio_event
. Answer and example: •
async for audio_event in rtc.AudioStream(track):
will yield frames while the track is active. • When the track is unpublished, the participant leaves, or the connection closes, the iterator stops and the loop exits — that signals end-of-stream. • Put cleanup or notification logic after the loop. Example:
Copy code
async def handle_audio_stream(track: rtc.Track):
    async for audio_event in rtc.AudioStream(track):
        frame = audio_event.frame
        # process frame...
    # loop exited → stream ended
    print("Audio stream ended for", track.name)
    # do cleanup/notify here
Optional: also listen for room track lifecycle events (
track_unpublished
,
participant_disconnected
) if you need proactive notifications before the iterator ends. Sources: Job lifecycle | LiveKit docs | Capturing the First Few Seconds of a Call for Processing | Subscribing to tracks | LiveKit docs
m
how to achieve the best tts stream processing and playback speed in the frontend livekit tts client, when the playbavk starts right after the first sentence arrived?
t
Goal: start playback as soon as the first sentence’s audio arrives while keeping subsequent audio smooth and low-latency. Key points and a minimal approach to implement. 1) Stream & emit as you synthesize • Push full sentences (or sentence-sized chunks) into the TTS stream so the engine emits audio per sentence. • Consume the TTS synthesized-audio concurrently on the backend and publish audio frames immediately (don’t buffer whole utterance). 2) Publish frames progressively into LiveKit • Use a single long-lived
rtc.AudioSource
and call
capture_frame()
for each synthesized frame as it arrives. • This lets the LiveKit SFU forward audio to clients immediately. 3) Frontend: play incremental frames with Web Audio API • Don’t recreate AudioContext per frame. Create one persistent AudioContext and a single playback node pipeline. • Option A (simple): create and start a BufferSource per incoming sentence frame, scheduling start at AudioContext.currentTime or slightly ahead to avoid gaps. • Option B (recommended for continuous low-latency): use an AudioWorklet (or ScriptProcessor fallback) with a FIFO queue of Float32 frames. Push frames into the queue as they arrive; the AudioWorklet pulls from the queue and outputs continuously — minimal gaps and low jitter. 4) Minimal buffering strategy • Keep a small jitter buffer (e.g., 40–100 ms) before playback start to absorb network jitter. • For first-sentence start, target ~40–60 ms buffer: start playback when you have ~2–3 10–30ms frames or when the first sentence’s audio chunk arrives (whichever you prefer). 5) Resampling / format • Ensure frames are the frontend sample rate (usually 48kHz). If backend sends 48kHz and frontend AudioContext is 48kHz, avoid resampling in browser. • Convert Int16 PCM -> Float32 in [-1,1] before feeding AudioBuffer/Worklet. 6) Handling segment boundaries & ordering • Include sequence number or timestamp metadata with frames so client can place frames in order. • On reorder or missing frames, the FIFO/Worklet can fill short gaps with silence to avoid clicks. 7) Practical TypeScript pattern (summary) • Create single AudioContext and AudioWorklet. • On first synthesized frame for a sentence: ◦ decode base64 → Int16Array → Float32Array ◦ push Float32Array to Worklet queue ◦ if playback not started, start worklet output after small warm-up buffer • For subsequent frames: continue pushing to queue. 8) Example pointers (concise) • Use AudioWorkletProcessor to implement pull-based playback. • Use postMessage or SharedArrayBuffer (if available) to transfer PCM efficiently to the worklet. • If you need a quick implementation without worklet, schedule small AudioBufferSourceNodes with start times offset by currentTime + smallLatency, but expect higher jitter. If you want, I can: • provide a minimal AudioWorklet + main-thread TypeScript snippet that consumes base64 pcm16 frames and plays them with a FIFO queue, or • give a simpler BufferSource-based snippet for quick testing. Which snippet would you like?
m
what happens when the elevenlabs plugin generates 200ms frame and the client in the frontend creates audio stream with 50ms frame size?
t
When ElevenLabs (backend) emits ~200 ms audio frames but the frontend requests/works with 50 ms frames, the system keeps playback smooth by buffering and splitting—you won’t need to manually slice frames. Key points: • Segmentation: the larger 200 ms chunk is split into smaller frames on the consumer side so your 50 ms processing loop still receives timely pieces. • Buffering/jitter: the client keeps a small buffer to smooth the split and network jitter. That buffer introduces a small, configurable latency (e.g., 40–100 ms). • Latency tradeoff: larger backend chunks can increase first-byte latency (you may wait up to the backend chunk duration before the first audio arrives). After the first chunk arrives, playback can start and proceed in 50 ms increments. • Ordering & gaps: include sequence numbers or timestamps (if available) to guard against reordering; the client should fill short gaps with silence to avoid clicks. • Resampling/format: ensure sample rate and channel count match (prefer 48 kHz mono to avoid extra resampling). • Performance: splitting in software is cheap; main impacts are slightly higher memory/buffer usage and potential longer time-to-first-sound. Practical guidance • Start playback after a small warm-up buffer (e.g., 2×50 ms = 100 ms) or immediately when the first sentence chunk arrives if you accept possible jitter. • Use an AudioWorklet FIFO (recommended) or schedule AudioBufferSourceNodes ahead using AudioContext.currentTime to avoid glitches. • If you need lower first-byte latency, reduce backend chunk size (if plugin/config allows) or have the backend emit the first small chunk faster. If you want, I can: • provide a short AudioWorklet FIFO example showing how to feed variable-size incoming frames and output fixed 50 ms buffers, or • show how to include/timestamp sequence numbers in your backend frames and handle them in the client. Which would you prefer? Sources: ElevenLabs TTS plugin guide | LiveKit Docs | Processing raw media tracks | LiveKit docs
m
my LiveKit TTS agent creates an audio `source with audio_source = rtc.AudioSource(…)`and captures audio frames from the Elevenlabs plugin with
audio_source.capture_frame(a.frame)
in the published track. my TS frontend LiveKit client connected to the same room as TTS agent. how to catch and process audio frames in the TS client and playback them in the browser?
t
Do you want a minimal TS example that (A) subscribes to the agent’s audio track and plays it automatically with
track.attach()
, or (B) pipes the track into WebAudio (AudioWorklet/ScriptProcessor) for custom processing before playback? Which one should I show? Sources: Subscribing to tracks | LiveKit docs | Realtime media | LiveKit Docs | Stream music over WebRTC using React and WebAudio
m
variant A
t
Great — here’s a minimal TypeScript example (variant A) that connects to a LiveKit room, subscribes to audio tracks, filters for your TTS agent, and plays the audio automatically using
track.attach()
.
Copy code
import { Room, RoomEvent, Track } from "livekit-client";

async function startPlayback(livekitUrl: string, token: string, ttsAgentIdentity: string) {
  const room = new Room();

  await room.connect(livekitUrl, token);

  // Attach any already-subscribed tracks (on reconnect)
  room.getTracks().forEach(pub => {
    const t = pub.track;
    if (t && t.kind === Track.Kind.Audio && pub.publisher === ttsAgentIdentity) {
      const audioEl = t.attach();
      audioEl.autoplay = true;
      document.body.appendChild(audioEl);
    }
  });

  // Play new tracks as they are subscribed
  room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
    if (track.kind === Track.Kind.Audio && participant.identity === ttsAgentIdentity) {
      const audioEl = track.attach();
      audioEl.autoplay = true;
      audioEl.controls = true; // optional
      document.body.appendChild(audioEl);
    }
  });

  // Remove audio elements when unsubscribed
  room.on(RoomEvent.TrackUnsubscribed, (track) => {
    const els = track.detach();
    els.forEach(el => el.remove());
  });

  // Optional: control volume per-track (0.0 - 1.0)
  room.on(RoomEvent.TrackSubscribed, (track, _, participant) => {
    if (track.kind === Track.Kind.Audio && participant.identity === ttsAgentIdentity) {
      try {
        track.setVolume(0.9); // 90%
      } catch {}
    }
  });

  return room;
}
Usage notes: • Replace
livekitUrl
,
token
, and
ttsAgentIdentity
with your values. •
track.attach()
returns an HTMLAudioElement that auto-plays decoded WebRTC audio — no manual decoding required. • Filter by
participant.identity
or by a publication
name
if you set one when publishing (use whichever reliably identifies your TTS agent).
m
room.getTracks().forEach(...)
--> Property getTracks does not exist on type Room
t
Thanks — the correct way is to iterate participants' track publications (Room has no getTracks()). Replace that part with participant-based access. Minimal corrected snippet:
Copy code
import { Room, RoomEvent, Track } from "livekit-client";

async function startPlayback(livekitUrl: string, token: string, ttsAgentIdentity: string) {
  const room = new Room();
  await room.connect(livekitUrl, token);

  // Attach already-published/subscribed tracks from remote participants
  room.remoteParticipants.forEach((participant) => {
    if (participant.identity !== ttsAgentIdentity) return;
    participant.trackPublications.forEach((pub) => {
      const t = pub.track;
      if (t && t.kind === Track.Kind.Audio) {
        const audioEl = t.attach();
        audioEl.autoplay = true;
        document.body.appendChild(audioEl);
      }
    });
  });

  // Play new tracks as they are subscribed
  room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
    if (track.kind === Track.Kind.Audio && participant.identity === ttsAgentIdentity) {
      const audioEl = track.attach();
      audioEl.autoplay = true;
      audioEl.controls = true;
      document.body.appendChild(audioEl);
    }
  });

  // Cleanup when unsubscribed
  room.on(RoomEvent.TrackUnsubscribed, (track) => {
    const els = track.detach();
    els.forEach(el => el.remove());
  });

  return room;
}
This uses
room.remoteParticipants
and
participant.trackPublications
to find already-available tracks. Sources: Rooms, participants, and tracks | LiveKit docs | Subscribing to tracks | LiveKit docs
m
how to simplify this if i have track.sid and track.name?
t
Use the publication (by sid or name) and the TrackSubscribed event — no full iteration needed. Minimal helper + usage: 1) Helper to get a publication by sid:
Copy code
function getPublicationBySid(room: Room, trackSid: string) {
  for (const p of room.remoteParticipants.values()) {
    const pub = p.trackPublications.get(trackSid);
    if (pub) return { pub, participant: p };
  }
  return null;
}
2) Helper to get a publication by name:
Copy code
function getPublicationByName(room: Room, trackName: string) {
  for (const p of room.remoteParticipants.values()) {
    for (const pub of p.trackPublications.values()) {
      if (pub.name === trackName) return { pub, participant: p };
    }
  }
  return null;
}
3) Ensure subscription and handle playback in TrackSubscribed:
Copy code
// request subscribe if we already know sid/name
const info = getPublicationBySid(room, KNOWN_SID) || getPublicationByName(room, KNOWN_NAME);
if (info && !info.pub.subscribed) {
  info.pub.setSubscribed(true);
}

// play when subscription becomes available
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
  if (publication.sid === KNOWN_SID || publication.name === KNOWN_NAME) {
    if (track.kind === Track.Kind.Audio) {
      const el = track.attach();
      el.autoplay = true;
      document.body.appendChild(el);
    }
  }
});
Notes: • Prefer
track.sid
(unique).
track.name
may not be unique. •
publication.track
exists only after subscription negotiation; use TrackSubscribed event to get the actual
track
. • You can call
publication.setSubscribed(true)
to trigger subscription if auto-subscribe is disabled. Sources: Rooms, participants, and tracks | LiveKit docs | Subscribing to tracks | LiveKit docs
m
how to how to get the moment when the first audio frame arrived?
t
Use the TrackSubscribed event to know the track is ready, then detect the very first audio samples with Web Audio (preferred) or by observing the created HTMLAudioElement’s playback events. Minimal, reliable approach — Web Audio non-silent detection: 1) On TrackSubscribed, create one persistent AudioContext and MediaStreamSource from the track’s MediaStreamTrack. 2) Connect an AnalyserNode or AudioWorklet that inspects the incoming buffers and triggers when you see non-zero audio (first real samples). 3) Run your "first frame arrived" action once, then connect the same MediaStreamSource to playback (or attach the track to an audio element). Example (TypeScript — Analyser-based detection):
Copy code
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
  if (track.kind !== Track.Kind.Audio) return;

  const mediaTrack = track.mediaStreamTrack;
  const stream = new MediaStream([mediaTrack]);
  const ac = new AudioContext();
  const source = ac.createMediaStreamSource(stream);

  const analyser = ac.createAnalyser();
  analyser.fftSize = 256;
  source.connect(analyser);

  const data = new Uint8Array(analyser.frequencyBinCount);
  let detected = false;

  const check = () => {
    analyser.getByteFrequencyData(data);
    const energy = data.reduce((s, v) => s + v, 0);
    if (!detected && energy > 0) {
      detected = true;
      console.log('first audio frame detected');
      // start your processing/playback logic here
      // e.g., attach for normal playback:
      const audioEl = track.attach();
      audioEl.autoplay = true;
      document.body.appendChild(audioEl);
      // cleanup analyser if not needed:
      source.disconnect(analyser);
      analyser.disconnect();
      return;
    }
    if (!detected) requestAnimationFrame(check);
  };
  check();
});
Notes and tips: • TrackSubscribed indicates the track is available but not necessarily that audio has arrived; Analyser checks the incoming stream for actual samples. • Use one AudioContext per page and reuse it to avoid limits and reduce latency. • For lower-level accuracy or lower latency, use an AudioWorklet that reads Float32 samples and signals on the first non-zero sample. • If you only need a coarse signal, the audio element’s
playing
event can also indicate audio started, but it’s less precise than examining samples. If you want, I can provide an AudioWorklet example that detects the first non-silent sample with lower jitter. Sources: Subscribing to tracks | LiveKit docs | Understanding &#34;silence detected on local audio track&#34; warning
m
show me how to detect it with the coarse signal of the audio element’s
playing
event
t
Use the audio element’s built-in events after calling
track.attach()
. The
playing
event is a coarse, cross-browser signal that playback has started (i.e., the first frames were received and decoded). Minimal example:
Copy code
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
  if (track.kind !== Track.Kind.Audio) return;

  // attach creates an HTMLAudioElement
  const audioEl = track.attach();
  audioEl.autoplay = true;
  audioEl.controls = true;
  document.body.appendChild(audioEl);

  // coarse detection: first playback start
  const onPlaying = () => {
    console.log('Audio playback started (coarse): first frames arrived');
    // do one-time actions here
    audioEl.removeEventListener('playing', onPlaying);
  };
  audioEl.addEventListener('playing', onPlaying);

  // optional: detect ended or pause
  audioEl.addEventListener('ended', () => console.log('audio ended'));
  audioEl.addEventListener('pause', () => console.log('audio paused'));
});
Notes: •
playing
fires when playback begins after having been paused or buffering; it’s not per-frame and may be delayed by browser buffering or autoplay restrictions. • Ensure user gesture/resume AudioContext or autoplay permissions to avoid blocked playback on some browsers.
m
it doesn’t work on the element from your example, created with
const audioEl = track.attach();
. why?
t
Thanks — good question. A few common reasons the
playing
event won’t fire on the audio element returned by
track.attach()
and how to fix them. Quick checklist to verify • The element must be added to the DOM (some browsers won’t start playback until element is in DOM). • Browser autoplay policies often block playback until a user gesture; ensure the element is allowed to play (call
audioEl.play()
after a user gesture or set
muted = true
temporarily for testing). • Confirm
audioEl
isn’t muted and volume is > 0 (muted elements may not emit
playing
). • Ensure the track is actually subscribed and has data (use console logs or Web Audio analyser to confirm audio presence). Working example (use after subscription)
Copy code
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
  if (track.kind !== Track.Kind.Audio) return;

  // attach() returns HTMLAudioElement but it must be added to DOM
  const audioEl = track.attach();
  audioEl.autoplay = true;
  audioEl.controls = true;
  document.body.appendChild(audioEl);

  // Some browsers require a user gesture to allow audible autoplay.
  // If autoplay is blocked, calling play() after a user gesture works:
  // await audioEl.play().catch(()=>{/* handle autoplay block */});

  const onPlaying = () => {
    console.log('coarse: audio playback started');
    audioEl.removeEventListener('playing', onPlaying);
  };
  audioEl.addEventListener('playing', onPlaying);

  // fallback: listen for 'canplay' or 'canplaythrough' which can fire earlier
  const onCanPlay = () => {
    console.log('canplay/canplaythrough fired');
  };
  audioEl.addEventListener('canplay', onCanPlay);
});
If
playing
still never fires: • Try
canplay
/
canplaythrough
— they often fire when enough data is buffered. • Temporarily
audioEl.muted = true
and call
audioEl.play()
to test autoplay blocking. If that makes
playing
fire, you have an autoplay policy issue. • Confirm the track actually has audio: create a small WebAudio analyser from the track’s MediaStreamTrack to detect non-silent data (this bypasses autoplay restrictions). If you want, share: • the browser and its autoplay settings, • whether you call
attach()
before or after adding to DOM, • and whether you see audio when manually attaching the element — I’ll give a tailored fix.
m
not the case — i hear the audio playback, but the element doesn’t fire
playing
event
t
Thanks — that helps. If you hear audio but the
playing
event never fires on the element returned by
track.attach()
, the most likely causes and reliable alternatives are: Why
playing
may not fire even though audio plays • The element returned by
track.attach()
may be a reused/shared element under the SDK; its ready/play state may already be past the moment that would dispatch
playing
by the time you add the listener. • Some browsers dispatch
playing
only once per lifecycle; if the element started buffered playback earlier, you miss the event. • Autoplay buffering/decoder behavior can cause
playing
to be suppressed in edge cases where playback is immediate from internal buffering. What to do (practical, minimal options) 1) Add the listener before attaching/starting playback (best fix)
Copy code
// create fresh audio element, add listener, then attach
const audioEl = document.createElement('audio');
audioEl.autoplay = true;
audioEl.controls = true;

const onPlaying = () => {
  console.log('playing fired');
  audioEl.removeEventListener('playing', onPlaying);
};

audioEl.addEventListener('playing', onPlaying);

// attach track's MediaStream to the element
audioEl.srcObject = new MediaStream([track.mediaStreamTrack]);
document.body.appendChild(audioEl);

// optionally call play() to ensure event fires (handle autoplay rejection)
audioEl.play().catch(()=>{/* may need user gesture */});
This ensures you don’t miss the event by creating and wiring the element yourself instead of relying on SDK-created elements. 2) Use
canplay
/
canplaythrough
as a coarser fallback • These often fire even when
playing
is missed:
Copy code
audioEl.addEventListener('canplay', () => console.log('canplay'));
3) Use the audio element’s timeupdate or first
currentTime
change • Listen for
timeupdate
or poll
audioEl.currentTime
to detect first advancement:
Copy code
const onTime = () => {
  if (audioEl.currentTime > 0) {
    console.log('first frame/time advanced');
    audioEl.removeEventListener('timeupdate', onTime);
  }
};
audioEl.addEventListener('timeupdate', onTime);
4) Most reliable and precise: detect samples with Web Audio • Create an AudioContext → MediaStreamSource(track.mediaStreamTrack) → AnalyserNode or AudioWorklet and look for non-zero samples. This is robust and low-latency. Quick Analyser example:
Copy code
const ac = new AudioContext();
const src = ac.createMediaStreamSource(new MediaStream([track.mediaStreamTrack]));
const analyser = ac.createAnalyser();
src.connect(analyser);
const data = new Uint8Array(analyser.frequencyBinCount);
const check = () => {
  analyser.getByteFrequencyData(data);
  if (data.some(v => v > 0)) {
    console.log('first samples detected');
  } else requestAnimationFrame(check);
};
check();
Which approach do you prefer? • I can give a full snippet that replaces
track.attach()
with a custom element wired for
playing
, or • provide the AudioWorklet example if you need very low-jitter, precise detection.
m
i send four sentences to the elevenlabs plugin in the agent. the agent streams received audio frames to the client. the audioEl on the client side plays two first sentences twice and the last two after it. what is the reason and how to fix?
t
Thanks — that must be frustrating. Below are the most likely causes and focused checks/fixes to stop the first two sentences from playing twice. Likely causes • Duplicate publishing: the agent accidentally publishes the same frames twice (e.g., calls
capture_frame()
twice or publishes the same track twice). • Multiple subscriptions/attachments: the client is subscribing or attaching the same remote track more than once (or creating two audio elements using the same MediaStreamTrack). • Republish on stream restart: your agent created a new LocalAudioTrack or re-published a track mid-utterance and the SFU delivered both streams briefly. • Frame ordering / buffering: the backend emitted the same early frames twice due to re-send/retry or a producer-buffer flush when the stream started. • Client queuing logic: if you buffer incoming chunks and then enqueue them twice (e.g., schedule same buffer twice when splitting a 200ms chunk into 100ms pieces). Quick diagnostic steps (run these first) 1. Server logging: log each
capture_frame()
call with a sequence id and text_index. Confirm frames for sentence 1–4 are emitted exactly once and in order. 2. Publication check: after publish, log room.local_participant.trackPublications to ensure only one published audio track exists. 3. Client subscription: log
TrackSubscribed
events, the
publication.sid
, and when you call
track.attach()
— ensure this happens only once per publication.sid. 4. Element count: inspect DOM for multiple audio elements referencing the same track (console.log(track.mediaStreamTrack.id) per element). 5. Frame metadata: if you include sequence/timestamp in frames, verify client reassembly uses them and doesn’t duplicate frames when splitting/concatenating. Concrete fixes • Ensure single publish path: ◦ Publish one
LocalAudioTrack
once and reuse its
AudioSource
for all
capture_frame()
calls. ◦ Don’t republish mid-utterance. • On agent: add per-frame sequence numbers /
text_index
to frames you capture and log them; avoid calling
capture_frame()
twice for the same frame. • On client: attach the track once. Use
TrackSubscribed
to attach and avoid any manual second attach: ◦ If you create your own audio element, don't also call
track.attach()
or vice versa. • If you split backend chunks, ensure split logic produces non-overlapping segments and client-side queue de-duplicates by sequence id. • If using reconnection/restart logic, ensure old audio elements/tracks are cleaned up before new ones are added (call
track.detach()
and remove elements). Minimal checklist to apply now • Add a frame counter on backend and print first 20 frames for the session. • Add console logs on client for TrackSubscribed, attach, and each audio element created (include mediaStreamTrack.id). • If duplicates confirmed server-side, prevent duplicate capture/publish. If duplicates are client-side, ensure single attach per publication. If you want, I can: • give a short server snippet that stamps frames with sequence+text_index, or • provide a client snippet that de-duplicates incoming frames/audio elements by publication.sid / sequence id. Which helper would you like?
m
give the both snippets
t
Backend (Python agent) — stamp/log frames and ensure single capture per synth frame:
Copy code
# backend_agent_snippet.py
import asyncio
from livekit import rtc
from livekit.agents import JobContext, WorkerOptions, cli

_audio_source = None

async def process_tts_stream(tts_stream):
    """Consume synthesized audio events and publish frames once each."""
    global _audio_source
    seq = 0
    async for synth in tts_stream.synthesized_audio():
        frame = synth.audio.frame
        # Log sequence + optional text_index for diagnostics
        print(f"[OUT] seq={seq} text_index={getattr(synth, 'text_index', -1)} samples={len(frame.data)//2}")
        # Ensure we call capture_frame exactly once per synth frame
        await _audio_source.capture_frame(frame)
        seq += 1

async def room_entrypoint(ctx: JobContext):
    global _audio_source
    room = ctx.room

    # publish one persistent AudioSource/track
    _audio_source = rtc.AudioSource(48000, 1)
    processed_track = rtc.LocalAudioTrack.create_audio_track("tts-output", _audio_source)
    await room.local_participant.publish_track(processed_track)

    # Example: create TTS stream and start processing (replace with your TTS creation)
    # tts_stream = tts.stream()
    # asyncio.create_task(process_tts_stream(tts_stream))
Frontend (TypeScript) — attach exactly once per publication.sid and optional seq-based dedupe placeholder:
Copy code
// frontend_dedupe_snippet.ts
import { Room, RoomEvent, Track } from "livekit-client";

export function attachOnceForPublication(room: Room, targetSid: string, targetName?: string) {
  const attached = new Set<string>();

  const tryAttach = (track: Track, publication, participant) => {
    if (publication.sid !== targetSid && publication.name !== targetName) return;
    if (attached.has(publication.sid)) return;
    if (track.kind !== Track.Kind.Audio) return;

    attached.add(publication.sid);
    const audioEl = track.attach();
    audioEl.autoplay = true;
    audioEl.controls = true;
    audioEl.dataset.pubSid = publication.sid;
    document.body.appendChild(audioEl);

    // cleanup on unsubscribed
    room.on(RoomEvent.TrackUnsubscribed, (t) => {
      if (t === track) {
        const els = track.detach();
        els.forEach(el => {
          if (el instanceof HTMLElement && el.dataset.pubSid === publication.sid) el.remove();
        });
        attached.delete(publication.sid);
      }
    });
  };

  // attach already-available subscribed track
  for (const participant of room.remoteParticipants.values()) {
    const pub = participant.trackPublications.get(targetSid);
    if (pub && pub.track) tryAttach(pub.track, pub, participant);
  }

  // attach when subscription occurs
  room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
    tryAttach(track, publication, participant);
  });
}

// Optional: if backend can send seq numbers via data messages, dedupe frames by seq:
// const lastSeqByPub = new Map<string, number>();
// function isDuplicate(pubSid: string, seq: number) {
//   const last = lastSeqByPub.get(pubSid);
//   if (last === seq) return true;
//   lastSeqByPub.set(pubSid, seq);
//   return false;
// }
Notes • Backend: logging seq/text_index confirms each synth frame is published exactly once; avoid multiple
capture_frame()
calls for the same synth frame. • Frontend: attach by unique
publication.sid
so you don’t create multiple audio elements for the same track. If duplication persists, send per-frame seq numbers (via data channel) from backend and use the optional dedupe logic on the client.
m
tts_stream.synthesized_audio()
--> synthesized_audio() doesn’t exist on tts_stream.
t
You're right —
synthesized_audio()
doesn't exist. Use the TTS stream as an async iterator. Minimal correct pattern and a focused checklist to avoid duplicates: Backend — consume TTS stream and publish exactly once per synth item
Copy code
async def publish_tts_to_source(tts_stream, audio_source):
    seq = 0
    async for synth in tts_stream:               # correct: async iterate the stream
        frame = synth.audio.frame                # rtc.AudioFrame
        # diagnostics
        print(f"[OUT] seq={seq} text_index={getattr(synth, 'text_index', -1)} samples={len(frame.data)//2}")
        # ensure a single capture_frame() call per synth item
        await audio_source.capture_frame(frame)
        seq += 1
Key backend checks • Only create one task that consumes this tts_stream; do not call
async for
on the same stream from multiple tasks. • Log
seq
/
text_index
per synth item to confirm each synth chunk is produced once. • Publish a single persistent `AudioSource`/LocalAudioTrack; don't re-publish mid-utterance. Frontend — attach once per publication and log events
Copy code
const attached = new Set<string>();

room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
  if (publication.sid !== TARGET_SID) return;
  if (attached.has(publication.sid)) return;   // guard: attach once
  if (track.kind !== Track.Kind.Audio) return;

  attached.add(publication.sid);
  const audioEl = track.attach();
  audioEl.autoplay = true;
  audioEl.controls = true;
  audioEl.dataset.pubSid = publication.sid;
  console.log("attached audio element for", publication.sid);
  document.body.appendChild(audioEl);
});
Frontend dedupe diagnostics • Log every TrackSubscribed and every attach call (print publication.sid and track.mediaStreamTrack.id). • If duplicates occur, check whether multiple attachments use the same mediaStreamTrack id (client-side duplication) or whether backend logs show duplicate seq entries (server-side duplication). If you want, I can: • provide a full end-to-end example wiring tts_stream → publish → client attach with per-frame seq logging, or • show a short snippet to send per-frame seq numbers to the client via data messages for client-side de-duplication. Which one would you like? Sources: Text-to-speech (TTS) models | LiveKit Docs