red-insurance-72205
08/12/2025, 3:52 AMtall-airline-16756
08/12/2025, 3:52 AMtall-airline-16756
08/12/2025, 3:53 AMBackgroundAudioPlayer
class from the livekit.agents.voice.background_audio
module. Let me walk you through how to set it up:
1. Import the Necessary Modules:
from livekit.agents.voice.background_audio import BackgroundAudioPlayer, BuiltinAudioClip
from livekit.agents import Agent, AgentSession
from livekit import rtc
2. Initialize the Background Audio Player:
player = BackgroundAudioPlayer(
ambient_sound=BuiltinAudioClip.OFFICE_AMBIENCE,
stream_timeout_ms=200
)
3. Start the Background Audio:
async def on_enter(self):
await player.start(room=self.room, agent_session=self.session)
4. Stop the Background Audio:
async def aclose(self) -> None:
await player.aclose()
Just a heads up—make sure your music is in a supported audio format. The BuiltinAudioClip
comes with some handy pre-recorded sounds, but if you want, you can also use your own audio files by passing the file path as a string.
And if you’re working on a web app, you can do something similar with the LiveKit JavaScript client by creating a media element and starting playback before joining the room. If you’d like, I’m here to help you with that too!
Sources: livekit-agents/livekit/agents/voice/background_audio.pyred-insurance-72205
08/12/2025, 3:57 AMtall-airline-16756
08/12/2025, 3:57 AMParticipantDisconnected
event—it tells you when someone leaves the room. For example:
room.addEventListener(RoomEvent.ParticipantDisconnected, (participant) => {
console.log('Participant disconnected:', participant.identity);
// Update UI or perform cleanup
});
2. Handle Empty Room State:
◦ Check if remoteParticipants
is empty to see if the room has no one left.
◦ Use emptyTimeout
to set how long the room stays open when empty—set it to 0
if you want it to close right away.
◦ You can also manually close the room anytime with closeIfEmpty()
.
1. Handle Room Disconnection:
Listen for the Disconnected
event on the room to catch when the room closes or participants disconnect:
room.addEventListener(RoomEvent.Disconnected, () => {
console.log('Disconnected from room');
// Clear UI and reset state
});
2. UI and Resource Cleanup:
◦ Make sure to remove participant elements from the UI and clear any video/audio tracks they were using.
◦ Show a friendly message letting everyone know the room is empty or disconnected.
Following these steps will help keep your room tidy and make sure everyone knows what’s going on when participants leave. If you want me to walk you through any part or need more details, just ask—I’m here to help!
Sources: src/room/Room.ts | lib/src/core/room.dart | pkg/rtc/room.go | Multiplatform/Controllers/RoomContext.swift | example/sample.ts