can we preload audio files for the BackgroundPlaye...
# ask-ai
a
can we preload audio files for the BackgroundPlayer? i have from time to time timeout for playing sounds effects
t
Thanks for reaching out, Sebastián. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking if you can preload audio for the BackgroundPlayer to avoid intermittent play timeouts — yes. What you can do: • Use local WAV files when possible — the BackgroundAudioPlayer uses an optimized custom decoder for WAV, which is fastest for small files. • Prewarm/load and decode audio during agent initialization (for example in your agent's
prewarm
or startup code) so the decoded audio is kept in memory and ready before you call
play()
. • If you must use non‑WAV formats, predecode them at startup (FFmpeg/PyAV is used at runtime for those formats, which can introduce delays). If you want, tell me: 1) which audio formats you’re using (WAV or other), 2) whether you control agent startup/prewarm code, and 3) an example of how/when you currently call
play()
. I can then suggest a specific preload pattern or code sketch for your setup. Sources: Agent speech and audio | LiveKit docs | Agent server options | LiveKit docs
a
i use a local WAV file of around 4s at 48khz i play it like this:
Copy code
async def play_notification_sound() -> None:
            """Play notification sound twice before agent speaks.

            Helper function to avoid code duplication across RPC methods.
            """
            if background_audio:
                logger.info("Playing notification sound twice")
                for i in range(2):
                    handle = background_audio.play(NOTIFICATION_AUDIO_FILE)
                    # Wait for the notification to finish playing
                    while handle and not handle.done():
                        await asyncio.sleep(0.1)
                    logger.debug(f"Notification sound {i + 1}/2 completed")
for now i don't have any prewarm actions
t
Thanks — that helps. You're using a local 4s WAV and calling
play()
on demand without prewarm. Here's a straightforward preload pattern and tips to avoid the timeouts. Recommended approach 1. Preload and decode the WAV at startup (prewarm) and keep the decoded buffer or a prepared handle ready. 2. On play, use the preloaded buffer so playback doesn't trigger file/decoder work. Minimal example pattern (async):
Copy code
# run at agent startup / prewarm
_preloaded_audio = None

async def prewarm_audio():
    global _preloaded_audio
    if not _preloaded_audio and background_audio:
        # load and decode into memory (BackgroundAudioPlayer API may accept a bytes-like buffer)
        with open(NOTIFICATION_AUDIO_FILE, "rb") as f:
            _preloaded_audio = f.read()

# playback using the preloaded bytes
async def play_notification_sound() -> None:
    if not background_audio:
        return
    logger.info("Playing notification sound twice")
    for i in range(2):
        handle = background_audio.play(_preloaded_audio)  # pass bytes/buffer instead of file path
        while handle and not handle.done():
            await asyncio.sleep(0.1)
        logger.debug(f"Notification sound {i + 1}/2 completed")
Notes and tips • Use WAV (you already are) — the optimized WAV decoder is fastest. • If
background_audio.play()
requires a filename and not raw bytes, keep a decoded in-memory variant if API supports it or open the file once and keep it ready for the player to read. • Call
await prewarm_audio()
during your agent startup or in a
prewarm
hook so the audio is loaded before first use. • If timeouts continue, increase the wait/poll loop interval slightly (e.g., 0.1s → 0.2s) or add a small delay between successive plays to avoid resource contention. If you want, tell me whether
background_audio.play()
accepts raw bytes or only file paths and I’ll give a precise code variant for that API.
a
Copy code
def play(
        self,
        audio: AudioSource | AudioConfig | list[AudioConfig],
        *,
        loop: bool = False,
    ) -> PlayHandle:
t
Thanks — you're using a local WAV and shared the
play()
signature. I'll focus on preloading a WAV into memory as frames and playing those frames so playback doesn't trigger file IO/decoding and cause timeouts. 1) Preload at startup (prewarm) into a list of `rtc.AudioFrame`:
Copy code
from livekit import rtc
from livekit.agents import utils

async def preload_wav(file_path: str) -> list[rtc.AudioFrame]:
    frames = []
    async for frame in utils.audio.audio_source_from_file(file_path):
        frames.append(frame)
    return frames
Call
await preload_wav(NOTIFICATION_AUDIO_FILE)
during your agent startup or
prewarm
and store the frames (e.g., in
ctx.proc.userdata["preloaded_sounds"]
). 2) Play the preloaded frames via an async generator so
background_audio.play()
receives an `AudioSource`/stream rather than a filename:
Copy code
async def audio_stream_from_frames(frames: list[rtc.AudioFrame], loop: bool = False):
    while True:
        for f in frames:
            yield f
        if not loop:
            break
3) Use those in your existing logic:
Copy code
# assume preloaded_frames is from preload_wav(...)
for i in range(2):
    handle = background_audio.play(audio_stream_from_frames(preloaded_frames, loop=False))
    while handle and not handle.done():
        await asyncio.sleep(0.1)
Notes and quick tips • WAV is optimal — LiveKit uses a fast WAV path, so preloading still reduces any remaining startup overhead. • Preload once per process/session; reuse the frames for every play to avoid repeated decoding. • Start preloading early (agent startup/prewarm) and ensure
background_audio
is started before first play. • If you still see timeouts, increase the poll interval slightly or add a short delay between plays. If you’d like, paste how you initialize
background_audio
and I’ll adapt the preload placement into your startup flow. Sources: Agent speech and audio | LiveKit docs | Silero VAD plugin | LiveKit docs
a
but should be done on on the prewarm function? this is the docs example:
Copy code
server = AgentServer()

def prewarm(proc: JobProcess):
    # load silero weights and store to process userdata
    proc.userdata["vad"] = silero.VAD.load()


server.setup_fnc = prewarm

@server.rtc_session()
async def my_agent(ctx: JobContext):
    # access the loaded silero instance
    vad: silero.VAD = ctx.proc.userdata["vad"]
t
Yes — put the preload in
prewarm
. That matches the docs pattern (load once into
proc.userdata
and reuse in sessions). Below is a minimal adaptation of your example showing how to preload the WAV as frames and use it in your agent. 1) Prewarm (load/decode once):
Copy code
from livekit import rtc
from livekit.agents import utils

def prewarm(proc: JobProcess):
    # schedule async preload on the process event loop
    async def _load():
        frames = []
        async for frame in utils.audio.audio_source_from_file(NOTIFICATION_AUDIO_FILE):
            frames.append(frame)
        proc.userdata["preloaded_notification"] = frames

    proc.loop.create_task(_load())
2) Use in your rtc session:
Copy code
async def audio_stream_from_frames(frames: list[rtc.AudioFrame], loop: bool = False):
    while True:
        for f in frames:
            yield f
        if not loop:
            break

@server.rtc_session()
async def my_agent(ctx: JobContext):
    preloaded = ctx.proc.userdata.get("preloaded_notification")
    # ensure background_audio is started/available before playing
    if preloaded and background_audio:
        for i in range(2):
            handle = background_audio.play(audio_stream_from_frames(preloaded, loop=False))
            while handle and not handle.done():
                await asyncio.sleep(0.1)
Notes: • Use
proc.userdata
so the frames are shared across sessions/process lifetime. • Start preloading early (in
prewarm
) so it's likely ready before first use; you can check for presence of
preloaded_notification
and await a short retry if needed. • Keep the frames in memory and reuse them to avoid file I/O and decoding at play time. Would you like a version that waits in the session until prewarm finishes (instead of using
proc.loop.create_task
) or help inserting this into your existing startup flow?
a
yes please
t
Good — below is a concise, ready-to-use pattern that preloads your WAV in
prewarm
, signals completion with an
asyncio.Event
, and waits in the session until prewarm finishes before playing. 1) Prewarm: load frames and set an Event when done
Copy code
import asyncio
from livekit import rtc
from livekit.agents import utils

NOTIFICATION_AUDIO_FILE = "/path/to/notification.wav"

def prewarm(proc: "JobProcess"):
    proc.userdata.setdefault("preloaded", {})
    proc.userdata["preloaded"]["event"] = asyncio.Event()

    async def _load():
        frames = []
        async for frame in utils.audio.audio_source_from_file(NOTIFICATION_AUDIO_FILE):
            frames.append(frame)
        proc.userdata["preloaded"]["frames"] = frames
        proc.userdata["preloaded"]["event"].set()

    proc.loop.create_task(_load())
2) Helper to stream frames
Copy code
async def audio_stream_from_frames(frames: list[rtc.AudioFrame], loop: bool = False):
    while True:
        for f in frames:
            yield f
        if not loop:
            break
3) RTC session: wait for preload (with timeout) then play
Copy code
@server.rtc_session()
async def my_agent(ctx: "JobContext"):
    pre = ctx.proc.userdata.get("preloaded", {})
    event: asyncio.Event | None = pre.get("event")
    frames: list[rtc.AudioFrame] | None = pre.get("frames")

    # Wait up to 5s for prewarm to finish (adjust timeout as needed)
    if event and not event.is_set():
        try:
            await asyncio.wait_for(event.wait(), timeout=5.0)
        except asyncio.TimeoutError:
            # fallback: load synchronously or skip playback
            frames = frames or []
    frames = frames or pre.get("frames") or []

    if not frames:
        # no preloaded frames available — fallback: play from file path
        handle = background_audio.play(NOTIFICATION_AUDIO_FILE)
    else:
        handle = background_audio.play(audio_stream_from_frames(frames, loop=False))

    # wait for completion
    while handle and not handle.done():
        await asyncio.sleep(0.1)
Notes: • The
Event
lets the session wait only as long as needed; adjust the
wait_for
timeout to suit your startup timing. • Keeping
frames
in
proc.userdata
reuses decoded frames across sessions and avoids file/decoder work at play time. • If preload fails or times out, the session falls back to playing the file path so behavior remains graceful. Want me to adapt this to your exact initialization (names/paths) or increase robustness (retries, logging)?
a
but this allows me to reuse the audio everytime?
t
Yes — storing the decoded WAV frames in
proc.userdata
during
prewarm
lets you reuse the audio every time you call
play()
. Key points and best practices: • Reuse: Keep the list of
rtc.AudioFrame
objects in
proc.userdata
and pass an async generator that yields those frames to
background_audio.play()
each time you need the sound. • Memory: A 4s 48k WAV is small, but preloading keeps decoded frames in memory — monitor memory if you preload many/large files. • Immutability: Treat the stored frames as read-only; yield copies or the same frames in sequence (frames can be yielded repeatedly for each play). • Concurrency: If multiple sessions may play the same frames concurrently, the async generator should simply iterate the stored frames independently for each play (no shared mutation), so concurrent playback works. • Fallback: Keep a fallback (play from filename) in case prewarm hasn't completed or frames failed to load. If you want, I can show a tiny snippet that demonstrates calling
play()
multiple times concurrently using the same preloaded frames.
a
increasing the stream timeout ms of the background audio player could help here?
t
Short answer: No — you cannot increase a stream timeout on BackgroundAudioPlayer. Instead, preload the WAV in
prewarm
and reuse the decoded frames (or an AudioSource) so playback never triggers on-demand file I/O/decoding. What to do (concise): • Preload in
prewarm
into
proc.userdata
(decode into a list of
rtc.AudioFrame
). • Signal completion with an
asyncio.Event
so sessions can wait (with a short timeout) for preload. • For each play, pass an async generator that yields the stored frames to
background_audio.play()
— this lets you reuse the same frames concurrently without redecoding. • Keep a small fallback to play from file if preload fails or times out. If you want, I can paste a final compact snippet that: 1) preloads into
proc.userdata
with an Event, 2) waits in the session with timeout, and 3) plays the preloaded frames (concurrent-safe). Which would you prefer — the full snippet or just the minimal changes to your current code? Sources: Agent speech and audio | LiveKit docs | Agent server options | LiveKit docs
a
what happens if an interruption occurs during the play handle? how can i know it was interrupted?
t
Regarding detecting interruptions of a `PlayHandle`: the player does not expose a built‑in
interrupted
flag. Interruptions are handled by the agent framework (e.g., thinking/ambient sounds stop when a turn begins), so you need to detect them in your application logic. How to detect/handle interruptions: • Keep the returned
PlayHandle
and stop it yourself when appropriate (call
handle.stop()
), and record that action in your code as an interruption. • Await completion normally with the handle; if you stop it yourself you know it was interrupted. • Observe agent/room lifecycle events (e.g., turn start, agent state changes, user events) that imply playback should be cancelled — treat those events as interruptions. • If you need explicit confirmation, implement a small state flag or callback: set a flag when you call
stop()
or when you see an interrupting event, and check it after
handle
finishes to determine whether completion was natural or interrupted. If you want, I can show a short snippet that wraps a
PlayHandle
to track interruption state and emit a callback when interrupted. Which language would you prefer (Python/asyncio)? Sources: Agent speech and audio | LiveKit docs | Turn detection and interruptions | LiveKit Docs