I'd like a context manager for playing the keyboar...
# ask-ai
n
I'd like a context manager for playing the keyboard background audio during specific segments of a call. Can you show me how to do this in python?
t
Thanks for reaching out, Stephen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand you're looking to play keyboard background audio using LiveKit. While LiveKit doesn’t have a built-in context manager for this, you can easily create one yourself using Python’s
asynccontextmanager
. Here’s a friendly example to guide you through it:
Copy code
import contextlib
from livekit.agents import BackgroundAudioPlayer, BuiltinAudioClip, AudioConfig

@contextlib.asynccontextmanager
async def keyboard_audio_context(room, agent_session, volume=0.8):
    """
    Context manager for playing keyboard typing audio during agent thinking.
    Automatically starts and stops the background audio player.
    """
    player = BackgroundAudioPlayer(
        thinking_sound=AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING, volume=volume)
    )
    await player.start(room=room, agent_session=agent_session)
    try:
        yield player
    finally:
        await player.aclose()
And here’s how you can use it:
Copy code
async with keyboard_audio_context(ctx.room, session) as bg_audio:
    await agent_session.say("Let me check that for you...")
    await asyncio.sleep(5)
This setup will take care of starting and stopping the audio automatically during that block of code. If you have any questions or need a hand with anything else, please don’t hesitate to reach out—I’m here to help! Sources: examples/voice_agents/background_audio.py
n
I previously tried it like this:
Copy code
@asynccontextmanager
async def keyboard_clacking():
    """
    Context manager that plays keyboard clacking background audio during the context.
    """
    handle: PlayHandle | None = None
    background_audio: BackgroundAudioPlayer | None = None
    try:
        background_audio = BackgroundAudioPlayer()
        handle = background_audio.play(audio=AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING, volume=0.8), loop=True)
        yield
    finally:
        if handle:
            handle.stop()
        if background_audio:
            await background_audio.aclose()
What's the difference between these two approaches?
t
Thanks so much for sharing your approach! The key difference between the two methods really comes down to how the audio system is initialized and managed: • Your approach: Uses
background_audio.play()
to play audio directly. This is great for on-demand playback of specific audio clips and gives you a
PlayHandle
for manual control. Just a heads-up, though—`play()` needs
start()
to have been called first to initialize the audio system. If
start()
hasn’t been called,
play()
will raise a
RuntimeError
. • My approach: Uses
background_audio.start()
to initialize the audio system and automatically manage ambient or “thinking” sounds based on the agent’s state. This is especially handy for continuous or event-driven playback since it ties directly into the agent’s lifecycle and doesn’t require you to manually control each audio clip. In your setup, if
play()
runs smoothly without calling
start()
explicitly, it might be because of some implicit initialization happening behind the scenes—but that’s not something we can always count on. My approach aims to make sure the audio system is properly started and cleaned up, which tends to be more reliable when managing background audio during specific parts of a call. Please feel free to reach out if you want me to explain anything further or help tweak your implementation—I’m here to help! Sources: examples/drive-thru/drivethru_agent.py | Agent speech and audio | LiveKit Docs
n
I assume starting up the background audio worker takes some memory and time. If I wanted to share the instance, where should I store it and how should I initialize it and clean it up
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
n
how am I supposed to close the background audio? I'm currently storing a reference to it on the userdata but don't know where to dispose of it
Should I use the
add_shutdown_callback
to close it?