Is there any way to dynamically compute how long t...
# ask-ai
c
Is there any way to dynamically compute how long the call went for? So I can save the same duration as the recording file I have.
t
Thanks for reaching out, Sebastian. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Could you help me understand a bit more about where you’re looking to calculate the call duration? Like, are you dealing with SIP calls, general LiveKit sessions, or something else? That way, I can give you advice that really fits your situation. Sources: pkg/stats/monitor.go | Sources/LiveKit/Protos/livekit_models.pb.swift | livekit-plugins/livekit-plugins-sarvam/livekit/plugins/sarvam/stt.py | SIP APIs | LiveKit Docs
c
This is my code right now. I have two issues: 1. The audio recording has like 20 extra seconds of blank audio 2. The way I compute the duration of the call is incorrect. For example, one call I calculated it lasted 54 seconds, but the audio file was actually 36 seconds and the call was actually like 10 seconds or something like that So I want to know how I can make everything work well. async def entrypoint(ctx: JobContext): metadata = get_job_metadata(ctx) prompt = metadata.get("prompt") or DEFAULT_INSTRUCTIONS initial_message = metadata.get("initial_message") or DEFAULT_INITIAL_MESSAGE model = metadata.get("model") or DEFAULT_MODEL session = AgentSession( stt=deepgram.STT(model="nova-3", language="en-US"), llm=openai.LLM(model=model), tts=elevenlabs.TTS(voice_id="cjVigY5qzO86Huf0OWal", model="eleven_flash_v2_5"), vad=ctx.proc.userdata["vad"], turn_detection=EnglishModel() ) SessionLocal = ctx.proc.userdata["db_sessionmaker"] agent_config_ref = agent_config_ref_from(metadata) call_uuid = uuid.uuid4() start_ts = time.time() await session.start( agent=Assistant(custom_instructions=prompt), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), close_on_disconnect=True, ), ) recording_key = f"{call_uuid}.ogg" await record_call(ctx, recording_key) async def _finalize(): duration = int(time.time() - start_ts) transcript = session.history.to_dict() transcript = json.loads(json.dumps(transcript, default=str)) async with SessionLocal() as s: logger.info("db_insert_start: call_id=%s", call_uuid) await create_call( s, agent_config_ref, call_id=call_uuid, started_at=datetime.utcfromtimestamp(start_ts), ended_at=datetime.utcnow(), duration_seconds=duration, recording_key=recording_key, recording_url=get_recording_url(recording_key), transcript=transcript, ) await ctx.connect() ctx.add_shutdown_callback(_finalize) await session.say( initial_message, add_to_chat_ctx=True, ) if name == "__main__": cli.run_app( WorkerOptions( entrypoint_fnc=entrypoint, prewarm_fnc=prewarm, agent_name='signalcore-agent', initialize_process_timeout=120 ) )
t
Let’s tackle the issues you're experiencing: 1. Extra blank audio: This usually happens because the agent and egress participants stay in the room even after the human participant leaves. To fix this, you can either delete the room when the human participant leaves or manually stop egress. Deleting the room is generally the easiest and best way to go. 2. Incorrect call duration: For a more accurate duration, you can use tools like
calculate_audio_duration
to measure the actual length of meaningful audio. Also, keeping an eye on participant join and leave events helps you figure out the real start and end times of the call. If you’d like, I’m happy to walk you through setting up room cleanup or handling participant events to make things smoother. Just let me know! Sources: livekit-plugins/livekit-plugins-silero/livekit/plugins/silero/vad.py
c
Give me a walkthrough on how to use the "Calculate audio duration"
t
Here’s a friendly guide on how you can use the
calculate_audio_duration
function to find the total length of your audio frames: Function Overview This handy function helps you calculate the total duration of audio frames in seconds. You can pass in either: • A single
rtc.AudioFrame
object • Or a list of
rtc.AudioFrame
objects Steps to Use 1. First, import the function:
Copy code
from livekit.agents.utils.audio import calculate_audio_duration
1. Then, use it with a single audio frame like this:
Copy code
import rtc
from livekit.agents.utils.audio import calculate_audio_duration

# Let’s say you have an AudioFrame
audio_frame = rtc.AudioFrame(data, sample_rate=48000, num_channels=1, samples_per_channel=480)
duration = calculate_audio_duration(audio_frame)
print(f"Duration: {duration} seconds")
1. Or, if you have multiple audio frames, you can do this:
Copy code
# If you’ve got several AudioFrames
audio_frames = [frame1, frame2, frame3]  # List of rtc.AudioFrame objects
total_duration = calculate_audio_duration(audio_frames)
print(f"Total duration: {total_duration} seconds")
How It Works The function figures out the duration by using this simple formula:
Copy code
duration = samples_per_channel / sample_rate
If you pass a list of frames, it just adds up the durations of each one. If you have any questions or want a hand with adding this to your code, just let me know—I’m here to help! Sources: livekit-plugins/livekit-plugins-sarvam/livekit/plugins/sarvam/stt.py | livekit-rtc/livekit/rtc/audio_frame.py
c
Hey sebastian hope you are doing well, can you please share how do you implemented the record_call function
t
I'd love to help you with the
record_call
function! Could you share a bit more about it? For instance, is it a custom function you've created, or are you asking about a specific feature in LiveKit? Understanding this will help me support you better.