narrow-chef-71655
11/26/2025, 10:20 AMtall-airline-16756
11/26/2025, 10:20 AMtall-airline-16756
11/26/2025, 10:20 AMlk load-test command to simulate publishers/subscribers, environment notes, and how to invoke it from Python.
1) Install the LiveKit CLI
• macOS (Homebrew): brew install livekit-cli
• Linux: curl -sSL https://get.livekit.io/cli | bash
• Windows: winget install LiveKit.LiveKitCLI
(Or download a prebuilt binary from the CLI releases.)
2) Run a basic load test from the shell Example — simulate 10 audio publishers and 1000 subscribers in room "load-test": lk load-test \ --url wss://your-livekit-server.com \ --api-key <your-api-key> \ --api-secret <your-api-secret> \ --room load-test \ --audio-publishers 10 \ --subscribers 1000
Example — simulate a 150-person video meeting: lk load-test \ --url wss://your-livekit-server.com \ --api-key <your-api-key> \ --api-secret <your-api-secret> \ --room load-test \ --video-publishers 150 \ --subscribers 150
Replace the URL, API key, and secret with your values.
3) Environment tips
• Run on a machine with sufficient CPU and network bandwidth.
• Increase file descriptor limit: ulimit -n 65535
• Prevent sleep/idle for long tests.
4) Call the CLI from Python Use subprocess to run lk load-test from a script or CI job. Example:
import subprocess
cmd = [
"lk", "load-test",
"--url", "wss://your-livekit-server.com",
"--api-key", "your-api-key",
"--api-secret", "your-secret",
"--room", "test-room",
"--video-publishers", "10",
"--subscribers", "50"
]
proc = subprocess.run(cmd, capture_output=True, text=True)
print(proc.stdout)
if proc.returncode != 0:
print("Error:", proc.stderr)
5) Notes
• The CLI uses WebRTC to simulate real participants for realistic results.
• If using LiveKit Cloud, tests count toward quotas/usage.
If you want, tell me:
• whether you’ll test on self-hosted LiveKit or LiveKit Cloud,
• target numbers (publishers/subscribers) and media type (audio/video),
and I’ll give a tailored command and recommended machine specs.
Sources: LiveKit CLI Setup | LiveKit Docs | Benchmarking | LiveKit docsnarrow-chef-71655
11/26/2025, 10:22 AMtall-airline-16756
11/26/2025, 10:22 AMnarrow-chef-71655
11/26/2025, 10:24 AMtall-airline-16756
11/26/2025, 10:24 AMnarrow-chef-71655
11/26/2025, 10:26 AMtall-airline-16756
11/26/2025, 10:26 AMnarrow-chef-71655
11/26/2025, 10:27 AMtall-airline-16756
11/26/2025, 10:27 AMlivekit-client or `livekit`; use your existing SDK package)
• soundfile or wave (for reading .wav)
• Use multiprocessing or run multiple containers to avoid single-process limits
Key configuration (fill with your values)
• LIVEKIT_WS = wss://your-livekit-server
• API_KEY / API_SECRET
• AUDIO_FILE = test_speech_5s.wav (mono PCM, 16-bit, 16k or 24kHz recommended)
• NUM_AGENTS = 100
• ROOMS = number of rooms to spread agents across (e.g., 10 → 10 agents/room)
Starter implementation (concise)
import asyncio
import os
import wave
from concurrent.futures import ThreadPoolExecutor
from livekit import Room, LocalAudioTrack, AudioSource, AccessToken, VideoGrant # adjust imports for your SDK
LIVEKIT_WS = os.getenv("LIVEKIT_WS", "wss://your-livekit-server")
API_KEY = os.getenv("LIVEKIT_API_KEY", "your-api-key")
API_SECRET = os.getenv("LIVEKIT_API_SECRET", "your-api-secret")
AUDIO_FILE = os.getenv("AUDIO_FILE", "test_speech_5s.wav")
NUM_AGENTS = int(os.getenv("NUM_AGENTS", "100"))
ROOM_BASE = os.getenv("ROOM_BASE", "loadtest-room")
ROOM_COUNT = int(os.getenv("ROOM_COUNT", "10"))
AGENT_DURATION = int(os.getenv("AGENT_DURATION", "60")) # seconds per agent run
def create_token(api_key, api_secret, room, identity):
at = AccessToken(api_key, api_secret, identity=identity)
at.add_grant(VideoGrant(room_join=True, room=room, can_publish=True, can_subscribe=True))
return at.to_jwt()
class LoopWave:
def __init__(self, path):
wf = wave.open(path, "rb")
self.sampwidth = wf.getsampwidth()
self.framerate = wf.getframerate()
self.nchannels = wf.getnchannels()
self.frames = wf.readframes(wf.getnframes())
wf.close()
# split into small 10ms frames
bytes_per_sample = self.sampwidth
frame_bytes = int(self.framerate * 0.01) * self.nchannels * bytes_per_sample
self.chunks = [self.frames[i:i+frame_bytes] for i in range(0, len(self.frames), frame_bytes)]
async def frames_iter(self):
while True:
for c in self.chunks:
yield c
async def run_agent(agent_idx, audio_loop):
room_name = f"{ROOM_BASE}-{agent_idx % ROOM_COUNT}"
identity = f"agent-{agent_idx}"
token = create_token(API_KEY, API_SECRET, room_name, identity)
room = Room() # adjust instantiation to SDK
await room.connect(LIVEKIT_WS, token)
# create local audio source/track (adjust to SDK API)
src = AudioSource(sample_rate=24000, channels=1)
track = LocalAudioTrack("agent-audio", src)
await room.local_participant.publish_track(track)
async def send_audio():
async for chunk in audio_loop.frames_iter():
# SDK-specific: capture or push PCM frame into source
await src.capture_frame(chunk, sample_rate=audio_loop.framerate, channels=audio_loop.nchannels)
await asyncio.sleep(0.01)
sender = asyncio.create_task(send_audio())
# keep alive to allow STT/LLM/TTS turnarounds
await asyncio.sleep(AGENT_DURATION)
sender.cancel()
await room.disconnect()
async def main():
audio_loop = LoopWave(AUDIO_FILE)
# run agents in batches to avoid stomping local resources
concurrency = 20
sem = asyncio.Semaphore(concurrency)
async def guarded(i):
async with sem:
await run_agent(i, audio_loop)
tasks = [asyncio.create_task(guarded(i)) for i in range(NUM_AGENTS)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Notes & recommendations
• Use mono PCM WAV at 16k–24kHz, 16-bit. The starter assumes 10ms frames.
• The SDK method names (Room, AudioSource, LocalAudioTrack, capture_frame, token classes) vary by package—adjust imports and calls to your installed LiveKit Python SDK.
• Run agents across multiple processes or containers to reach 100 concurrent agents reliably. Example: 4 processes × 25 agents each.
• Monitor CPU, memory, and network bandwidth. Increase ulimits: ulimit -n 65535.
• Spread agents across multiple rooms (ROUNDS) to balance per-room bandwidth.
• Add logging to measure STT/transcription latency and TTS response times (timestamps when publish occurs and when a response track is received).
• If you hit media/ICE issues in headless environments, ensure NAT/ICE/STUN/TURN settings are correct and reachable.
If you want, I can:
• produce a tested code sample matching your exact installed Python SDK (tell me the package name/version), or
• provide a multiprocessing/container orchestration snippet (Docker Compose) to run 100 agents across processes.
Which would you like next?narrow-chef-71655
11/26/2025, 10:30 AMtall-airline-16756
11/26/2025, 10:31 AMimport asyncio
import os
import wave
from collections import deque
from livekit import Room, AccessToken, VideoGrant, LocalAudioTrack, AudioSource # adjust imports
LIVEKIT_WS = os.getenv("LIVEKIT_WS", "wss://your-livekit-server")
API_KEY = os.getenv("LIVEKIT_API_KEY", "key")
API_SECRET = os.getenv("LIVEKIT_API_SECRET", "secret")
NUM_AGENTS = int(os.getenv("NUM_AGENTS", "100"))
ROOM_BASE = os.getenv("ROOM_BASE", "loadtest-room")
ROOM_COUNT = int(os.getenv("ROOM_COUNT", "10"))
EPOCH_DELAY = float(os.getenv("EPOCH_DELAY", "10.0")) # seconds
AGENT_DURATION = int(os.getenv("AGENT_DURATION", "120"))
def create_token(api_key, api_secret, room, identity):
at = AccessToken(api_key, api_secret, identity=identity)
at.add_grant(VideoGrant(room_join=True, room=room, can_publish=True, can_subscribe=True))
return at.to_jwt()
class AudioBuffer:
def __init__(self, max_seconds=30, sample_rate=24000, channels=1, chunk_ms=10):
self.sample_rate = sample_rate
self.channels = channels
self.chunk_bytes = int(sample_rate * (chunk_ms/1000.0)) * 2 * channels # 16-bit PCM
max_chunks = int(max_seconds * 1000 / chunk_ms)
self.deque = deque(maxlen=max_chunks)
def push(self, pcm_bytes):
self.deque.append(pcm_bytes)
def drain(self):
data = b"".join(self.deque)
self.deque.clear()
return data
async def handle_agent(agent_idx, target_identity=None):
room_name = f"{ROOM_BASE}-{agent_idx % ROOM_COUNT}"
identity = f"agent-{agent_idx}"
token = create_token(API_KEY, API_SECRET, room_name, identity)
room = Room()
await room.connect(LIVEKIT_WS, token)
# Create a local audio source/track (SDK-specific)
src = AudioSource(sample_rate=24000, channels=1)
local_track = LocalAudioTrack("agent-publish", src)
await room.local_participant.publish_track(local_track)
# Choose subscription target; here we subscribe to the first remote participant that appears
audio_buffer = AudioBuffer(sample_rate=24000)
@room.on("track_subscribed")
def on_track_subscribed(track, participant):
# Only handle audio tracks
if track.kind != "audio":
return
# Hook into incoming audio frames - SDK-specific callback
async def on_frame(frame):
# frame.data is raw PCM bytes; push to buffer
audio_buffer.push(frame.data)
track.on("frame", on_frame) # adjust for SDK event API
# wait for initial subscriptions to stabilize
await asyncio.sleep(1)
async def epoch_loop():
while True:
await asyncio.sleep(EPOCH_DELAY)
# drain buffer and publish it as a new local track (or replace source)
pcm = audio_buffer.drain()
if not pcm:
continue
# Option A: push PCM into the existing AudioSource
# Many SDKs expose a capture_frame-like API:
await src.capture_frame(pcm, sample_rate=24000, channels=1)
# Option B: if SDK requires a new track, create and publish one with pcm
# After publishing, allow time for agent worker to process (STT/LLM/TTS)
await asyncio.sleep(1) # small grace before next epoch
coro = asyncio.create_task(epoch_loop())
# keep agent alive for AGENT_DURATION then cleanup
await asyncio.sleep(AGENT_DURATION)
coro.cancel()
await room.disconnect()
async def main():
concurrency = 20
sem = asyncio.Semaphore(concurrency)
async def guarded(i):
async with sem:
await handle_agent(i)
tasks = [asyncio.create_task(guarded(i)) for i in range(NUM_AGENTS)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Implementation notes and adjustments you must make
• SDK events/callbacks differ: replace track.on("frame", ...), AudioSource.capture_frame, and Room usage with the exact methods in your installed LiveKit Python client.
• Frame encoding: ensure incoming frames are delivered as raw PCM. If SDK gives encoded RTP packets, use SDK helpers that provide decoded audio frames or configure the subscriber to provide raw audio frames.
• If the SDK doesn’t expose direct raw frames on subscription, you can subscribe and have the agent worker publish a mirrored track that your load-test clients can also subscribe to; or use server-side mixing/forwarding logic.
• Buffer sizing: tune chunk size and buffer length to match EPOCH_DELAY and memory limits.
• Concurrency: run multiple processes/containers to hit 100 agents. Example: spawn N worker processes each running this script with NUM_AGENTS / N agents.
• Latency metrics: timestamp when buffer drained and when a response track is received to measure STT→LLM→TTS roundtrip.
If you want, I can next:
• produce the same example adapted to the exact Python LiveKit package version you have installed (tell me the package name/version), or
• provide a multiprocessing launcher/docker-compose snippet to run 100 agents across multiple processes. Which next step do you want?narrow-chef-71655
11/26/2025, 10:34 AMimport asyncio
import time
from livekit import rtc
from livekit.rtc import RemoteTrackPublication, RemoteParticipant, Track
class LoadTestRoom:
def __init__(self, echo_speech_delay, index, logger=None):
self.echo_speech_delay = echo_speech_delay
self.index = index
self.room: rtc.Room = rtc.Room()
self.echo_source = rtc.AudioSource(48000, 1)
self.echo_track = rtc.LocalAudioTrack.create_audio_track(
"echo-track",
self.echo_source
)
self.running = True
self.first_received = False
self.logger = logger
async def connect(self, url: str, token: str):
await self.room.connect(url, token)
self.room.on("track_subscribed", self._on_track_subscribed)
# Create the echo track (same as Go)
await self.room.local_participant.publish_track(self.echo_track)
if self.logger:
self.logger.info(f"[Room {self.index}] Echo participant connected.")
def _on_track_subscribed(self, track: Track, publication: RemoteTrackPublication,
participant: RemoteParticipant):
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
if self.first_received:
return
self.first_received = True
remote_audio = track
if self.logger:
self.logger.info(f"[Room {self.index}] Subscribed to agent audio.")
asyncio.create_task(self._echo_audio(remote_audio))
async def _echo_audio(self, remote_audio: Track):
queue = asyncio.Queue(maxsize=2000)
audio_stream = rtc.AudioStream(remote_audio)
async def reader():
async for event in audio_stream: # event = AudioFrameEvent
self.logger.info(f"[Room {self.index}] Received event AudioFram in Reader")
await queue.put((event, time.time()))
if not self.running:
break
async def writer():
while self.running:
self.logger.info(f"[Room {self.index}] Start Point audio received.")
event, ts = await queue.get()
self.logger.info(f"[Room {self.index}] Going for delay event {event}.")
delay = self.echo_speech_delay - (time.time() - ts)
if delay > 0:
await asyncio.sleep(delay)
self.logger.info(f"[Room {self.index}] Echo audio received.")
# IMPORTANT FIX
await self.echo_source.capture_frame(event.frame)
await asyncio.gather(reader(), writer())
async def stop(self):
self.running = False
await self.room.disconnect()
if self.logger:
self.logger.info(f"[Room {self.index}] Disconnected.")
this is how i have written but it is not working nothing is being publish on user track
INFOloadtest[Room 4] Start Point audio received.
INFOloadtest[Room 4] Going for delay event AudioFrameEvent(frame=rtc.AudioFrame(sample_rate=48000, num_channels=1, samples_per_channel=480, duration=0.010)).
INFOloadtest[Room 4] Echo audio received.tall-airline-16756
11/26/2025, 10:35 AMcapture_frame with try/except and log errors.
• Increase AudioSource buffer (queue_size_ms) to avoid blocking/failing to capture.
• Ensure you publish the local track before relying on capture_frame (you already do).
• Optionally filter by participant.identity to ensure you subscribe to the intended agent.
Corrected _echo_audio (concise)
async def _echo_audio(self, remote_audio: Track):
queue = asyncio.Queue(maxsize=2000)
audio_stream = rtc.AudioStream(remote_audio)
async def reader():
try:
async for event in audio_stream:
if not self.running:
break
await queue.put((event.frame, time.time()))
except Exception as e:
self.logger.error(f"[Room {self.index}] reader error: {e}")
finally:
# signal end of stream
await queue.put((None, 0))
async def writer():
while True:
try:
item = await asyncio.wait_for(queue.get(), timeout=1.0)
except asyncio.TimeoutError:
if not self.running and queue.empty():
break
continue
frame, ts = item
if frame is None:
break
delay = self.echo_speech_delay - (time.time() - ts)
if delay > 0:
await asyncio.sleep(delay)
try:
await self.echo_source.capture_frame(frame)
except Exception as e:
self.logger.error(f"[Room {self.index}] capture_frame failed: {e}")
finally:
queue.task_done()
self.logger.info(f"[Room {self.index}] writer exiting")
await asyncio.gather(reader(), writer())
AudioSource creation suggestion (increase queue size)
• When you create the AudioSource, set a larger buffer (if constructor supports it):
self.echo_source = rtc.AudioSource(48000, 1, queue_size_ms=2000)
(if your SDK’s constructor param name differs, adjust accordingly)
Extra debugging tips
• Log participant.identity in _on_track_subscribed to ensure you subscribe to the correct agent.
• Log success of publish: after publish_track, log returned publication or SID.
• Add a short sleep after publish to ensure the track is fully negotiated before you start capturing: await asyncio.sleep(0.2)
• Monitor exceptions from capture_frame — they show if the source buffer is full or if the track isn’t published.
If you want, I can:
• produce a minimal end-to-end example with AudioSource creation and publish flow matching your installed livekit Python package version (tell me the package name/version), or
• add participant identity filtering and a graceful shutdown example. Which would help most? Sources: client-sdk-android | livekit/livekit_composite | DeepWiki | Subscribing to tracks | LiveKit docs | Camera & microphone | LiveKit docs | Processing raw media tracks | LiveKit docs | Resolving "InvalidState - failed to capture frame" errors in AudioSourcenarrow-chef-71655
11/26/2025, 10:48 AMtall-airline-16756
11/26/2025, 10:49 AMframe.data (int16 PCM) to numbers, compute RMS or dB, and skip frames below a threshold (e.g. -50 dB).
• Cheap, fast, no extra deps.
Example (insert into your reader loop):
import numpy as np
def is_silent(frame, threshold_db=-50.0):
samples = np.frombuffer(frame.data, dtype=np.int16).astype(np.float32)
if samples.size == 0:
return True
rms = np.sqrt((samples**2).mean()) + 1e-10
db = 20 * np.log10(rms / 32768.0)
return db < threshold_db
# usage inside reader:
async for event in audio_stream:
if is_silent(event.frame):
continue
await queue.put((event.frame, time.time()))
2) Use a VAD for better accuracy (recommended)
• Use a VAD model (e.g., Silero VAD in LiveKit plugins or any VAD) to get speech probability per frame and only buffer frames when speech is detected.
• More robust to background noise and tuning.
Concept:
# pseudo: use your VAD API to check frame
speech_prob = await vad_stream.recv_audio(event.frame)
if speech_prob > 0.5:
await queue.put((event.frame, time.time()))
Integration tips for your echo logic
• Buffer only non-silent frames, but keep short leading/trailing silence (e.g., keep N ms before/after speech) to avoid clipped words.
• If you want epoch-based behavior (collect X seconds of spoken audio every epoch), use VAD to mark speech segments, append silent padding around segments, then on epoch end drain and publish only the buffered speech region.
• Keep writer alive and robust (use timeout on queue.get) so brief silent gaps don’t stop the loop.
• Monitor queue sizes and use queue_size_ms on AudioSource to avoid capture_frame failures.
Example pattern for epoch with VAD/energy:
• reader: discard silent frames until speech starts, then push frames to queue while speech continues (and for a short trailing timeout).
• epoch task (every epoch_delay): drain queue → if drained buffer non-empty, publish via capture_frame (or push frames into AudioSource).
If you want, I can:
• adapt the RMS code into your existing _echo_audio (full patch), or
• produce an example using the Silero VAD plugin for more reliable detection. Which would you prefer? Sources: Bringing Zoom's end-to-end optimizations to WebRTC | examples/dtmf | livekit/livekit_composite | DeepWiki | Resolving "InvalidState - failed to capture frame" errors in AudioSource | Subscribing to tracks | LiveKit docs | Processing raw media tracks | LiveKit docsnarrow-chef-71655
11/26/2025, 10:56 AMtall-airline-16756
11/26/2025, 10:57 AMself.echo_source.capture_frame() accepts an AudioFrame or raw PCM wrapped into rtc.AudioFrame.
1) Buffering approach (store frames and timestamps)
# inside _echo_audio: replace per-frame immediate capture with epoch buffering
EPOCH_SEC = 30.0
frame_buffer = [] # list of rtc.AudioFrame or raw bytes
epoch_start = time.time()
async def reader():
async for event in audio_stream:
if not self.running:
break
# optional: skip silent frames here
frame_buffer.append(event.frame)
# continue reading without publishing
async def epoch_publisher():
while self.running:
await asyncio.sleep(EPOCH_SEC)
if not frame_buffer:
continue
# Create a snapshot and clear buffer atomically
frames_to_send = frame_buffer.copy()
frame_buffer.clear()
# publish frames_to_send sequentially to preserve timing
for f in frames_to_send:
try:
await self.echo_source.capture_frame(f)
except Exception as e:
self.logger.error(f"[Room {self.index}] capture_frame failed: {e}")
# preserve original frame duration (10ms)
await asyncio.sleep(f.duration)
2) If capture_frame requires raw PCM instead of AudioFrame:
• Convert frames_to_send into rtc.AudioFrame objects with correct metadata, or if you have raw bytes, package them into a single long AudioFrame with samples_per_channel = sample_rate * epoch_seconds (but many SDKs expect small frames; prefer sequential 10ms frames).
3) Optional: silence trimming and padding
• Before sending, you can trim leading/trailing silent frames (use RMS or VAD) and add a small pre/post padding (e.g., 100–300ms) to avoid clipped words.
4) Use separate tasks and proper locking
• Protect access to shared frame_buffer with an asyncio.Lock if reader and publisher run concurrently:
buffer_lock = asyncio.Lock()
# when appending:
async with buffer_lock:
frame_buffer.append(event.frame)
# when draining:
async with buffer_lock:
frames_to_send = frame_buffer.copy()
frame_buffer.clear()
5) Timing and pacing
• Use await asyncio.sleep(frame.duration) between captures to avoid flooding the AudioSource; do not call capture_frame back-to-back without pacing.
• Keep AudioSource queue_size_ms large enough (e.g., 2000) to handle bursts.
6) Memory considerations
• 30s of 48kHz mono int16 ~= 48000 * 2 * 30 = ~2.88 MB per agent. For 100 agents, ensure host has enough RAM or reduce epoch size/sample rate.
If you’d like, I can:
• convert this into a complete replacement _echo_audio function matching your earlier class (with lock, VAD filter, and asyncio tasks), or
• show how to stitch frames into a single long AudioFrame if your SDK prefers that. Which do you want?narrow-chef-71655
11/26/2025, 10:58 AMtall-airline-16756
11/26/2025, 10:58 AMAudioFrame objects into a thread-safe buffer for an epoch (30s),
• drains the buffer at epoch end and publishes the collected audio sequentially to your AudioSource (preserving timing),
• optionally trims leading/trailing silent frames (RMS-based) before publishing,
• uses an asyncio.Lock to avoid races, and includes basic error handling.
Adjust SDK method names if your installed package differs.
import asyncio
import time
import numpy as np
EPOCH_SECONDS = 30.0
SILENCE_DB_THRESHOLD = -50.0 # tune as needed
def is_silent_frame(frame, threshold_db=SILENCE_DB_THRESHOLD):
samples = np.frombuffer(frame.data, dtype=np.int16).astype(np.float32)
if samples.size == 0:
return True
rms = np.sqrt((samples**2).mean()) + 1e-10
db = 20 * np.log10(rms / 32768.0)
return db < threshold_db
async def _echo_audio(self, remote_audio: Track):
audio_stream = rtc.AudioStream(remote_audio)
buffer_lock = asyncio.Lock()
frame_buffer = [] # list of rtc.AudioFrame
reader_done = False
async def reader():
nonlocal reader_done
try:
async for event in audio_stream:
if not self.running:
break
frame = event.frame
# optional: skip silent frames to reduce buffer size
if is_silent_frame(frame):
continue
async with buffer_lock:
frame_buffer.append(frame)
except Exception as e:
self.logger.error(f"[Room {self.index}] reader error: {e}")
finally:
reader_done = True
async def epoch_publisher():
while self.running or not reader_done:
await asyncio.sleep(EPOCH_SECONDS)
# snapshot and clear buffer atomically
async with buffer_lock:
if not frame_buffer:
continue
frames_to_send = frame_buffer.copy()
frame_buffer.clear()
# Optional: trim leading/trailing silence from frames_to_send (already filtered above)
# Publish frames sequentially, preserving timing
for f in frames_to_send:
try:
await self.echo_source.capture_frame(f)
except Exception as e:
self.logger.error(f"[Room {self.index}] capture_frame failed: {e}")
# consider retry/backoff or dropping remaining frames
# preserve original per-frame duration (e.g., 0.01s)
await asyncio.sleep(f.duration)
self.logger.info(f"[Room {self.index}] Published {len(frames_to_send)} frames (~{len(frames_to_send)*frames_to_send[0].duration:.1f}s)")
# start tasks
reader_task = asyncio.create_task(reader())
publisher_task = asyncio.create_task(epoch_publisher())
await asyncio.gather(reader_task, publisher_task)
Important notes and tuning
• Memory: 30s @ 48kHz mono int16 ≈ 2.88 MB per agent. For 100 agents, ensure enough RAM or reduce epoch/sample-rate.
• Timing: we publish frames sequentially with await asyncio.sleep(f.duration) to keep real-time pacing. Do not flood capture_frame without pacing.
• AudioSource buffer: ensure AudioSource was created with a sufficient internal buffer (e.g., queue_size_ms=2000) to avoid capture_frame blocking/failing.
• Silence handling: you can increase sensitivity or use a VAD for better detection; if you want exact original silence preserved, remove the is_silent_frame filter.
• Synchronization: use the Lock to avoid race conditions between reader and publisher.
• Graceful shutdown: ensure self.running = False triggers exit; publisher drains remaining frames before exit.
Would you like a full, runnable minimal example adapted to your exact livekit-client package version (tell me the package name/version) or a version that writes the 30s buffer to a WAV and publishes that single long AudioFrame?