python agents sdk how to start and stop audio play...
# ask-ai
f
python agents sdk how to start and stop audio playback inside tool execution
t
Thanks for reaching out, Dmitry. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to start and stop audio playback (input/output) from inside a Python Agents SDK tool — here’s how to do that. Use the session controls on the RunContext to toggle audio input (listening) and output (speech) during your tool execution:
Copy code
@function_tool()
async def my_tool(self, context: RunContext):
    # stop listening and stop speaking
    context.session.input.set_audio_enabled(False)
    context.session.output.set_audio_enabled(False)

    try:
        # do your work while audio is paused
        await do_something()
    finally:
        # always re-enable audio
        context.session.input.set_audio_enabled(True)
        context.session.output.set_audio_enabled(True)
If you only need to pause one direction: • Pause listening only:
context.session.input.set_audio_enabled(False)
• Pause speaking only:
context.session.output.set_audio_enabled(False)
Place re-enable calls in a
finally
block so audio resumes even if an error occurs. For runnable examples, see the Toggle Audio and Long Running tools examples in the agents repo. Would you like an example that mutes output for a fixed timeout or one that mutes until an event completes? Sources: Text and transcriptions | LiveKit docs | Tool definition and use | LiveKit docs
f
no, I need to play background audio
t
You're asking how to play background audio during a tool's execution with the Python Agents SDK — use the BackgroundAudioPlayer. Short example and key options: 1) Create the player (ambient + thinking clips optional)
Copy code
from livekit.agents import BackgroundAudioPlayer, AudioConfig, BuiltinAudioClip

background_audio = BackgroundAudioPlayer(
    ambient_sound=AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6),
    thinking_sound=[AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING, volume=0.7)],
)
2) Start it after connecting the room and session
Copy code
await background_audio.start(room=ctx.room, agent_session=ctx.session)
3) Play a custom file during a tool and stop when done
Copy code
@function_tool()
async def my_tool(self, ctx: RunContext):
    handle = ctx.background_audio.play("/path/to/bg.mp3")  # returns PlayHandle
    try:
        await do_long_work()
    finally:
        handle.stop()           # stop early if needed
You can also await the handle to wait until playback finishes:
await handle
. Notes: •
thinking_sound
will automatically play during tool execution if configured. • Supported sources: local files (MP3/WAV), built-in clips, or an async audio frame iterator. Do you want an example that loops ambient audio only, or one that mixes ambient + intermittent thinking clips during execution? Sources: External data and RAG | LiveKit Docs | Agent speech and audio | LiveKit docs | LiveKit Docs
f
I want to play standard audio, like HOLD_MUSIC
t
You can play “hold music” by using BackgroundAudioPlayer with either a local audio file (recommended) or a built-in clip (there is no
HOLD_MUSIC
enum). Quick steps and example: 1. Create/start the player (after you have room + session)
Copy code
from livekit.agents import BackgroundAudioPlayer

background_audio = BackgroundAudioPlayer()
await background_audio.start(room=ctx.room, agent_session=ctx.session)
1. Play your hold music (local file) during a tool, and stop when done
Copy code
@function_tool()
async def my_tool(self, ctx: RunContext):
    handle = ctx.background_audio.play("/path/to/hold_music.mp3")  # returns PlayHandle
    try:
        await do_long_work()
    finally:
        handle.stop()
Notes: • Built-in clips (e.g.,
BuiltinAudioClip.OFFICE_AMBIENCE
) can be used but there is no built-in
HOLD_MUSIC
. •
play()
supports local MP3/WAV/etc., built-in clips, or an async audio-frame iterator. • You can
await handle
to wait for playback to finish or call
handle.stop()
to end early. Do you have a local file you want to use, or should I show an example using a built-in clip? Sources: Agent speech and audio | LiveKit docs
f
ok show me example with OFFICE_AMBIENCE
t
You want an example that plays the built-in
OFFICE_AMBIENCE
clip as background audio during a tool run. Below is a minimal Python Agents SDK example showing setup, starting the player, and playing the built-in clip while a tool executes.
Copy code
import asyncio
from livekit.agents import BackgroundAudioPlayer, AudioConfig, BuiltinAudioClip
from livekit.agents.llm import function_tool
from livekit.agents.context import RunContext

# Create and configure the background audio player (once, e.g., at startup)
background_audio = BackgroundAudioPlayer(
    ambient_sound=AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6)
)

# After you connect to the room and have an agent session, start the player:
# await background_audio.start(room=ctx.room, agent_session=ctx.session)

# Example tool that ensures ambient audio plays during execution
@function_tool()
async def my_long_tool(self, ctx: RunContext):
    # If the player was started with the session, ambient SOUND will already be active.
    # Optionally play the built-in clip on demand (returns PlayHandle)
    handle = ctx.background_audio.play(AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6))

    try:
        # Simulate long-running work while ambience plays
        await asyncio.sleep(10)
        return "Done"
    finally:
        # Stop the on-demand playback if still running
        handle.stop()
Notes: • If you want continuous ambient audio across the session, set
ambient_sound
when creating the player and call
await background_audio.start(room=ctx.room, agent_session=ctx.session)
. •
ctx.background_audio.play(...)
accepts
AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=...)
for on-demand playback. • Use
await handle
to wait for playback to finish or
handle.stop()
to end early. Would you like a version that loops ambient audio only (no on-demand play) or one that mixes ambient + intermittent thinking clips?
f
AttributeError: 'RunContext' object has no attribute 'background_audio'
t
You're seeing that AttributeError because
RunContext
doesn't include
background_audio
by default. You must create the BackgroundAudioPlayer yourself and make it accessible to tools — either attach it to your Agent instance or store it in
session.userdata
. Below are two minimal patterns. Option A — attach to your Agent (recommended)
Copy code
from livekit.agents import Agent, BackgroundAudioPlayer, AudioConfig, BuiltinAudioClip
from livekit.agents.llm import function_tool
import asyncio

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="...")
        self.background_audio = BackgroundAudioPlayer(
            ambient_sound=AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6)
        )

    @function_tool()
    async def long_task(self, ctx):
        # ensure player started with room/session earlier
        handle = self.background_audio.play(AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6))
        try:
            await asyncio.sleep(5)
            return "done"
        finally:
            handle.stop()
Start the player after connecting:
Copy code
# after creating agent and session
await agent.background_audio.start(room=ctx.room, agent_session=ctx.session)
await session.start(agent=agent, room=ctx.room)
Option B — store player in session.userdata
Copy code
# during setup
bg = BackgroundAudioPlayer()
ctx.session.userdata.background_audio = bg
await bg.start(room=ctx.room, agent_session=ctx.session)

# inside a tool
@function_tool()
async def long_task(self, ctx):
    bg = ctx.session.userdata.background_audio
    handle = bg.play(AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6))
    try:
        await asyncio.sleep(5)
    finally:
        handle.stop()
Use
context.agent.background_audio
if attached to the agent, or
context.session.userdata.background_audio
if stored in userdata. Which pattern fits your app (agent-level or per-session) so I can tailor a full example? Sources: Tool definition and use | LiveKit docs | Agent speech and audio | LiveKit docs
f
the music doesn't stop why ? I can see log
Hold music stopped
Copy code
try:
            # Play hold music if background audio player is available
            if self._background_audio_player:
                play_handle = self._background_audio_player.play(
                    AudioConfig(BuiltinAudioClip.HOLD_MUSIC, volume=0.5),
                    loop=True
                )
                logger.info("Hold music started")
            
            # Wait for the specified duration
            await asyncio.sleep(timeInSeconds)
        finally:
            # Stop the hold music when done if it was started
            if play_handle is not None:
                play_handle.stop()
                logger.info("Hold music stopped")
            else:
                logger.info("Hold music not stopped, play_handle is None")
t
Thanks — I can help troubleshoot. You're seeing the "Hold music stopped" log but audio keeps playing; that means the play handle stop was called but the playback didn't actually end. A few likely causes and checks, plus a corrected pattern to ensure stop takes effect. Checks to run • Confirm the BackgroundAudioPlayer was started with the room and session before calling `.play()`: await background_audio.start(room=ctx.room, agent_session=ctx.session) • Ensure the returned object from
.play()
is the actual PlayHandle (not None). Log
play_handle
right after play to verify. • If you used
loop=True
, verify the PlayHandle.stop() cancels looped playback (it should). Confirm no other concurrent
.play()
calls are creating separate handles. • Check for exceptions hiding before the finally block — ensure
play_handle
is in scope (define it before try). Corrected safe pattern
Copy code
play_handle = None
try:
    if self._background_audio_player:
        play_handle = await self._background_audio_player.play(
            AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.5),
            loop=True
        )
        logger.info("Hold music started: %s", play_handle)

    await asyncio.sleep(timeInSeconds)

finally:
    if play_handle is not None:
        # some implementations require awaiting stop or calling .stop() then awaiting completion
        play_handle.stop()
        # optionally await completion if PlayHandle is awaitable
        try:
            await asyncio.wait_for(play_handle, timeout=2.0)
        except Exception:
            logger.debug("Play handle did not finish awaiting or timed out")
        logger.info("Hold music stopped")
    else:
        logger.info("Hold music not stopped, play_handle is None")
Extra things to verify • Is
play()
async? In some examples
play()
returns an awaitable PlayHandle — use
play_handle = await background_audio.play(...)
. If you called it without await you may have a partial/invalid handle. • Are there multiple BackgroundAudioPlayer instances (e.g., one on agent and one in userdata)? Stopping one won't stop another. • Browser/participant caching: confirm the client stopped receiving the audio track (inspect participant audio stream). If the audio is being published continuously by another source, stopping this handle won't remove that other source. • Ensure no other code restarts playback after your stop (search for other
.play()
calls). If you share: • How you create/start the BackgroundAudioPlayer (where and when you call
.start()
), • Whether you
await
the
.play()
call, • The exact PlayHandle type/log output, I can point to the specific line to fix. Which of those details can you paste?
f
async def on_enter(self): # Initialize scratchpad with session info scratchpad = get_scratchpad() # Initialize background audio player for hold music job_ctx = get_job_context() self._background_audio_player = BackgroundAudioPlayer() await self._background_audio_player.start(room=job_ctx.room, agent_session=self.session) @function_tool() async def wait( self, context: RunContext, timeInSeconds: int, ) -> dict: """Wait for a given number of seconds. Plays hold music during the wait.""" logger.info(f"Waiting for {timeInSeconds} seconds with hold music") play_handle = None try: # Play hold music if background audio player is available if self._background_audio_player: play_handle = self._background_audio_player.play( AudioConfig(BuiltinAudioClip.HOLD_MUSIC, volume=0.5), loop=True ) logger.info("Hold music started") # Wait for the specified duration await asyncio.sleep(timeInSeconds) finally: # Stop the hold music when done if it was started if play_handle is not None: play_handle.stop() logger.info("Hold music stopped") else: logger.info("Hold music not stopped, play_handle is None") return {"message": f"Waited for {timeInSeconds} seconds. Ready to continue."}
t
Thanks — I see the issue. You’re logging “Hold music stopped” but audio keeps playing. Key fixes (short) and a corrected minimal example. Main fixes • Await the play call:
play_handle = await player.play(...)
—
play()
is awaitable and must be awaited so the handle is valid. • After calling
play_handle.stop()
, also await the handle to ensure playback fully finishes:
await play_handle
. • Ensure the BackgroundAudioPlayer was started once with the room and session and you’re stopping the same handle instance (no duplicate players). Corrected pattern
Copy code
# created once (e.g., in on_enter)
self._background_audio_player = BackgroundAudioPlayer()
await self._background_audio_player.start(room=job_ctx.room, agent_session=self.session)

# inside your tool
play_handle = None
try:
    if self._background_audio_player:
        play_handle = await self._background_audio_player.play(
            AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.5),
            loop=True
        )
        logger.info("Hold music started")
    await asyncio.sleep(timeInSeconds)
finally:
    if play_handle is not None:
        play_handle.stop()
        try:
            await play_handle
        except asyncio.CancelledError:
            pass
        logger.info("Hold music fully stopped")
    else:
        logger.info("Hold music not stopped, play_handle is None")
Extra checks if it still persists • Confirm you awaited
play()
(most common cause). • Ensure
BuiltinAudioClip.HOLD_MUSIC
exists in your SDK; if not, use a file path (e.g.,
"/path/hold.mp3"
) or a confirmed built-in like
OFFICE_AMBIENCE
. • Verify you aren’t creating multiple BackgroundAudioPlayer instances or calling
.play()
elsewhere. • Confirm the agent/session remains connected while stopping playback. If you paste the exact log of the
play_handle
(print its repr) and confirm whether you used
await
on
play()
, I’ll point to the precise line to change. Which audio source are you using now —
HOLD_MUSIC
enum or a local file? Sources: Agent speech and audio | LiveKit docs
f
from your documentation Gracefully closes the background audio system, canceling all ongoing playback tasks and unpublishing the audio track.
def *play*(self,
audio: AudioSource | AudioConfig | list[AudioConfig], *, loop: bool = False) ‑> PlayHandle Expand source code
Copy code
def play(
    self,
    audio: AudioSource | AudioConfig | list[AudioConfig],
    *,
    loop: bool = False,
) -> PlayHandle:
    
"""
  # noqa: E501
    if not self._mixer_atask:
        raise RuntimeError("BackgroundAudio is not started")

    normalized = self._normalize_sound_source(audio)
    if normalized is None:
        play_handle = PlayHandle()
        play_handle._mark_playout_done()
        return play_handle

    sound_source, volume = normalized

    if loop and isinstance(sound_source, AsyncIterator):
        raise ValueError(
            "Looping sound via AsyncIterator is not supported. Use a string file path or your own 'infinite' AsyncIterator with loop=False"  # noqa: E501
        )

    play_handle = PlayHandle()
    task = asyncio.create_task(self._play_task(play_handle, sound_source, volume, loop))
    task.add_done_callback(lambda _: self._play_tasks.remove(task))
    task.add_done_callback(lambda _: play_handle._mark_playout_done())
    self._play_tasks.append(task)
    return play_handle
Plays an audio once or in a loop. Args audio (Union[AudioSource, AudioConfig, List[AudioConfig]]): The audio to play. Can be: - A string pointing to a file path - An AsyncIterator that yields
rtc.AudioFrame
- An AudioConfig object with volume and probability - A list of AudioConfig objects, where one will be selected based on probability
Copy code
If a string is provided and <code>loop</code> is True, the sound will be looped.
If an AsyncIterator is provided, it is played until exhaustion (and cannot be looped
automatically).
loop (bool, optional): Whether to loop the audio. Only applicable if
audio
is a string or contains strings. Defaults to False. Returns
PlayHandle
An object representing the playback handle. This can be awaited or stopped manually.
t
Thanks — good catch. From the code you pasted,
play()
is synchronous and returns a
PlayHandle
(not awaitable). Adjustments to make stop reliable: 1) Await play task completion after stopping • Call
play_handle.stop()
then await the handle to let the playback task finish:
Copy code
play_handle.stop()
try:
    await play_handle
except asyncio.CancelledError:
    pass
2) Ensure you keep the returned handle • Define
play_handle = None
before try and assign the returned handle synchronously:
Copy code
play_handle = None
if self._background_audio_player:
    play_handle = self._background_audio_player.play(..., loop=True)
3) Keep a single BackgroundAudioPlayer instance • Start it once with
start(room, agent_session)
and reuse it. Stop one handle doesn’t stop other concurrent handles or other player instances. 4) Loop semantics •
loop=True
only works for string file paths (or configs containing strings). AsyncIterator sources cannot be looped. Minimal corrected pattern based on the real API:
Copy code
play_handle = None
try:
    if self._background_audio_player:
        # play() returns PlayHandle synchronously
        play_handle = self._background_audio_player.play(
            "/path/to/hold_music.mp3", loop=True
        )
        logger.info("Hold music started")

    await asyncio.sleep(timeInSeconds)

finally:
    if play_handle is not None:
        play_handle.stop()         # request stop
        try:
            await play_handle      # wait for underlying task to finish
        except asyncio.CancelledError:
            pass
        logger.info("Hold music fully stopped")
    else:
        logger.info("Hold music not stopped, play_handle is None")
If you still hear audio after this: • Confirm the
audio
you passed is a file path or AudioConfig with a file string (so loop works). • Verify there are no other active play handles or duplicate BackgroundAudioPlayer instances publishing audio. • Print/log
play_handle
repr and inspect
self._background_audio_player._play_tasks
to see active tasks. Would you like me to review the actual runtime logs or play_handle repr you’re seeing?
f
how to initialise only 1 background audio player
t
Do this once and reuse it — create the BackgroundAudioPlayer at agent/session startup, guard so you don't recreate it, start it with the room+session, then reference that single instance from tools (via
self
or
session.userdata
). Minimal example and tips: Option A — attach to Agent (recommended)
Copy code
from livekit.agents import Agent, BackgroundAudioPlayer, AudioConfig, BuiltinAudioClip
from livekit.agents.llm import function_tool
import asyncio

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="...")
        self._background_audio_player = None
        self._bg_started = False

    async def on_enter(self, job_ctx):
        # create + start only once
        if self._background_audio_player is None:
            self._background_audio_player = BackgroundAudioPlayer(
                ambient_sound=AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.6)
            )
        if not self._bg_started:
            await self._background_audio_player.start(room=job_ctx.room, agent_session=self.session)
            self._bg_started = True

    @function_tool()
    async def wait(self, ctx, timeInSeconds: int) -> dict:
        play_handle = None
        try:
            if self._background_audio_player:
                play_handle = self._background_audio_player.play(
                    AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.5),
                    loop=True
                )
            await asyncio.sleep(timeInSeconds)
        finally:
            if play_handle:
                play_handle.stop()
                try:
                    await play_handle
                except asyncio.CancelledError:
                    pass
        return {"message": f"Waited {timeInSeconds}s"}
Option B — store in session.userdata (useful if you don’t control Agent instance)
Copy code
# setup once in your entrypoint after ctx.connect()
bg = BackgroundAudioPlayer()
ctx.session.userdata.background_audio = bg
await bg.start(room=ctx.room, agent_session=ctx.session)

# in tools:
@function_tool()
async def wait(self, ctx: RunContext, timeInSeconds: int):
    bg = ctx.session.userdata.background_audio
    handle = bg.play("/path/to/hold.mp3", loop=True)
    try:
        await asyncio.sleep(timeInSeconds)
    finally:
        handle.stop()
        try:
            await handle
        except asyncio.CancelledError:
            pass
Best practices • Initialize once (guard with a flag or check for existing attribute). • Start the player with
start(room, agent_session)
once after connecting. • Always stop the same PlayHandle and
await
it to ensure playback ends. • Avoid creating multiple BackgroundAudioPlayer instances or calling
.play()
from multiple places simultaneously unless intended. • If you need global access, put the player on
self
(agent) or
session.userdata
— don’t attach it to RunContext. Tell me which pattern you prefer (Agent vs session.userdata) and I’ll adapt the snippet to your app structure.