I have a track egress request with ```request = ap...
# ask-ai
r
I have a track egress request with
Copy code
request = api.TrackEgressRequest(
                room_name=self.ctx.room.name,
                track_id=track_sid,
                file=api.DirectFileOutput(
                    filepath=filepath,
                    s3=api.S3Upload(
                        access_key=os.getenv("AWS_ACCESS_KEY_ID"),
                        secret=os.getenv("AWS_SECRET_ACCESS_KEY"),
                        region=os.getenv("AWS_REGION"),
                        bucket=os.getenv("AWS_BUCKET_NAME"),
                    ),
                ),
            )

            # Start the egress
            egress_info = await self.livekit_api.egress.start_track_egress(request)
it has a long silence in the end. I assume this is because the room is still open and the agent is connected. Is that so? Is there a way to terminate this egress early?
t
Thanks for reaching out, Ivan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're correct — the silence appears because the track/room remains active, so Track Egress keeps recording until the track is unpublished or the egress is stopped. What you can do now • Stop the egress programmatically using the egress ID returned when you started it:
Copy code
await self.livekit_api.egress.stop_egress(
    livekit.StopEgressRequest(egress_id=egress_info.egress_id)
)
This immediately finalizes the file (including the S3 upload) and prevents appended silence. Ways to avoid silent tails going forward • Stop egress when the participant leaves: listen for
participant_left
and call StopEgress for that track. • Stop egress when the track is unpublished: listen for
track_unpublished
and stop the egress for that track. • Delete the room when the session is over: deleting the room removes participants and stops any active egress. If you want, tell me which event source you use (webhooks or in-app events) and I’ll show a short example for detecting the participant/track end and calling StopEgress. Sources: Track egress | LiveKit docs | Egress API | LiveKit docs | Webhooks | LiveKit docs
r
what is the best event to use? I want the egress to stop immediately after participant disconnects
t
For stopping Track Egress immediately when a participant disconnects, use the participant_left event (webhook or in-app event). It fires as soon as the participant leaves the room, so you can call StopEgress right away and avoid any trailing silence. Example flow 1. Listen for the
participant_left
event for the participant whose track you’re egressing. 2. When received, call StopEgress with the egress_id returned when you started the egress:
Copy code
await self.livekit_api.egress.stop_egress(
    livekit.StopEgressRequest(egress_id=egress_info.egress_id)
)
Notes and alternatives • If you prefer to react specifically when the track stops publishing (rather than the participant leaving), use
track_unpublished
.
participant_left
is best when you want immediate stop on disconnect. Would you like a short webhook handler example for
participant_left
in Python or Node?
r
how about
room.on("participant_disconnected")
?
t
Yes —
room.on("participant_disconnected")
is appropriate for stopping Track Egress immediately when a participant leaves the client-side room. It fires as soon as that participant disconnects from the room session, so you can call StopEgress there to avoid trailing silence. Quick notes: • Use
participant_disconnected
when you want the client or server SDK reacting in real time to a participant leaving. • If you need a server-side, out-of-process trigger (e.g., your egress controller runs separately), use the
participant_left
webhook instead. • If you care about the track specifically being unpublished (rather than the participant disconnecting), use
track_unpublished
. Example (JS) — call StopEgress when participant disconnects:
Copy code
room.on("participant_disconnected", async (participant) => {
  // map participant -> egressId you started earlier, then:
  await livekitApi.egress.stopEgress({ egress_id: egressId });
});
Example (Python) pattern:
Copy code
def on_participant_disconnected(participant):
    # lookup egress_id for this participant's track
    await livekit_api.egress.stop_egress(livekit.StopEgressRequest(egress_id=egress_id))
Would you like a concrete snippet showing how to store/lookup the
egress_id
per participant in your app?
r
livekit_api.egress.stop_egress is async, so I need to await, how to handle async
on_participant_disconnected
?
t
You're right to note
stop_egress
is async — you need to run it in an async context. Below are concise patterns for handling that in both Python and JavaScript depending on how your event handler system works. Python (async event loop) • If your handler can be async, make it async and await directly:
Copy code
async def on_participant_disconnected(participant):
    egress_id = lookup_egress_id(participant.identity)
    if egress_id:
        await livekit_api.egress.stop_egress(
            livekit.StopEgressRequest(egress_id=egress_id)
        )
• If the event system expects a sync callback, schedule the async call without blocking:
Copy code
def on_participant_disconnected(participant):
    egress_id = lookup_egress_id(participant.identity)
    if egress_id:
        asyncio.create_task(
            livekit_api.egress.stop_egress(
                livekit.StopEgressRequest(egress_id=egress_id)
            )
        )
Use
asyncio.create_task
so the stop runs in background; handle exceptions inside the coroutine or add a wrapper that awaits and logs errors. JavaScript (browser / Node) • If the handler supports async functions, await directly:
Copy code
room.on("participant_disconnected", async (participant) => {
  const egressId = lookupEgressId(participant.sid);
  if (egressId) {
    await livekitApi.egress.stopEgress({ egress_id: egressId });
  }
});
• If you prefer not to block the event loop, call and ignore the returned promise (but catch errors):
Copy code
room.on("participant_disconnected", (participant) => {
  const egressId = lookupEgressId(participant.sid);
  if (egressId) {
    livekitApi.egress.stopEgress({ egress_id: egressId })
      .catch(err => console.error("Stop egress failed", err));
  }
});
Storing/lookup tip • Keep a map keyed by participant SID/identity to the
egress_id
when you start egress, and remove it on stop. That lets your handler find the right egress to stop immediately. If you tell me which runtime (asyncio server, Flask, FastAPI, browser, or Node) you’re using, I can provide a short tailored snippet.
r
can I egress in
wav
format?
t
You cannot export Track Egress directly as WAV. Track Egress saves audio as the original WebRTC format (Opus in an Ogg container) when writing to file. What you can do • Export raw PCM via WebSocket and encode to WAV on your server (audio arrives as
pcm_s16le
frames). • Or export the
.ogg
file and convert it to WAV after upload (FFmpeg example below). FFmpeg conversion example 1. From Ogg/Opus to WAV:
Copy code
ffmpeg -i input.ogg -ar 16000 -ac 1 output.wav
1. From raw PCM (
pcm_s16le
) to WAV:
Copy code
ffmpeg -f s16le -ar 16000 -ac 1 -i input.pcm output.wav
If you tell me whether you prefer WebSocket (server-side real‑time PCM) or converting uploaded files, I can provide a short example for that flow and suggested sample rates/channel settings. Sources: Track egress | LiveKit docs | Egress API | LiveKit docs | Capturing the First Few Seconds of a Call for Processing