magnificent-furniture-90167
12/04/2025, 9:34 AMtall-airline-16756
12/04/2025, 9:34 AMtall-airline-16756
12/04/2025, 9:37 AMpcm_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 Egressmagnificent-furniture-90167
12/04/2025, 9:38 AMtall-airline-16756
12/04/2025, 9:38 AMpcm_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:
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 WebRTCmagnificent-furniture-90167
12/04/2025, 9:49 AMtall-airline-16756
12/04/2025, 9:50 AMrtc.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.
# 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".
// 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 Processingmagnificent-furniture-90167
12/04/2025, 10:07 AMprocessed_bytes have the valid values?tall-airline-16756
12/04/2025, 10:08 AMprocessed_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:
if not processed_bytes:
raise ValueError("empty audio payload")
• Length aligned to 16-bit samples:
if len(processed_bytes) % 2 != 0:
raise ValueError("byte length not multiple of 2")
2) Interpret as int16 and check dtype/shape
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]
if pcm.min() < -32768 or pcm.max() > 32767:
raise ValueError("sample values out of int16 range")
• Detect heavy clipping (many samples at max/min):
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
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)
# 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:
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
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?magnificent-furniture-90167
12/04/2025, 10:17 AMtall-airline-16756
12/04/2025, 10:17 AMmagnificent-furniture-90167
12/04/2025, 10:26 AMpcm_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?tall-airline-16756
12/04/2025, 10:26 AMnp.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:
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:
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:
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:
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?magnificent-furniture-90167
12/04/2025, 10:30 AMtall-airline-16756
12/04/2025, 10:30 AM@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:
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).
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:
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 docsmagnificent-furniture-90167
12/04/2025, 10:52 AMtall-airline-16756
12/04/2025, 10:53 AMpcm_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
// 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?magnificent-furniture-90167
12/10/2025, 1:49 PMtall-airline-16756
12/10/2025, 1:50 PMmagnificent-furniture-90167
12/10/2025, 2:54 PMtall-airline-16756
12/10/2025, 2:55 PMend_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:
# 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 Docsmagnificent-furniture-90167
12/11/2025, 7:02 AM# 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?tall-airline-16756
12/11/2025, 7:02 AMtext_index, text, or a segment/completed flag).
Example (Python) — listen for segment events while pushing text:
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 Docsmagnificent-furniture-90167
12/11/2025, 7:31 AMtall-airline-16756
12/11/2025, 7:31 AMend_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.magnificent-furniture-90167
12/11/2025, 8:45 AMtall-airline-16756
12/11/2025, 8:45 AM@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
# 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)
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).
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?magnificent-furniture-90167
12/11/2025, 9:06 AMtall-airline-16756
12/11/2025, 9:06 AMtts_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:
# 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 docsmagnificent-furniture-90167
12/11/2025, 10:18 AMtall-airline-16756
12/11/2025, 10:18 AMawait 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:
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?magnificent-furniture-90167
12/11/2025, 1:39 PM# 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?tall-airline-16756
12/11/2025, 1:40 PMaudio_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:
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 docsmagnificent-furniture-90167
12/12/2025, 2:47 PMtall-airline-16756
12/12/2025, 2:48 PMrtc.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?magnificent-furniture-90167
12/12/2025, 2:59 PMtall-airline-16756
12/12/2025, 3:00 PMmagnificent-furniture-90167
12/17/2025, 12:15 PMaudio_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?tall-airline-16756
12/17/2025, 12:15 PMtrack.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 WebAudiomagnificent-furniture-90167
12/17/2025, 12:29 PMtall-airline-16756
12/17/2025, 12:30 PMtrack.attach().
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).magnificent-furniture-90167
12/17/2025, 2:28 PMroom.getTracks().forEach(...) --> Property getTracks does not exist on type Roomtall-airline-16756
12/17/2025, 2:29 PMimport { 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 docsmagnificent-furniture-90167
12/17/2025, 2:43 PMtall-airline-16756
12/17/2025, 2:44 PMfunction 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:
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:
// 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 docsmagnificent-furniture-90167
12/18/2025, 8:45 AMtall-airline-16756
12/18/2025, 8:46 AMroom.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 "silence detected on local audio track" warningmagnificent-furniture-90167
12/18/2025, 1:47 PMplaying eventtall-airline-16756
12/18/2025, 1:47 PMtrack.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:
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.magnificent-furniture-90167
12/18/2025, 1:59 PMconst audioEl = track.attach(); . why?tall-airline-16756
12/18/2025, 2:00 PMplaying 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)
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.magnificent-furniture-90167
12/18/2025, 2:01 PMplaying eventtall-airline-16756
12/18/2025, 2:01 PMplaying 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)
// 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:
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:
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:
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.magnificent-furniture-90167
12/18/2025, 2:57 PMtall-airline-16756
12/18/2025, 2:58 PMcapture_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?magnificent-furniture-90167
12/18/2025, 4:26 PMtall-airline-16756
12/18/2025, 4:27 PM# 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:
// 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.magnificent-furniture-90167
12/18/2025, 4:45 PMtts_stream.synthesized_audio() --> synthesized_audio() doesn’t exist on tts_stream.tall-airline-16756
12/18/2025, 4:46 PMsynthesized_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
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
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