i want to save the transcripts in my db how can i ...
# ask-ai
s
i want to save the transcripts in my db how can i do that? also i need no of seconds and record the call
t
Thanks for reaching out, ABHIRAM. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to help you save transcripts in your database! You can capture real-time events like
user_input_transcribed
or grab the full conversation history using
session.history
once the session ends. From there, storing this data in your database is straightforward with your usual database drivers. For tracking call duration, here are a couple of friendly tips: • You can use
RECOGNITION_USAGE
events from STT plugins such as Deepgram or FireworksAI to monitor how long the audio was transcribed. • Another way is to track the session duration by noting when participants connect and disconnect. If you'd like, I’m here to guide you through setting up database integration or event listeners—just let me know! Sources: Session recording and transcripts | LiveKit Docs | docs/index.yaml | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt_v2.py
s
i need agent code for this
t
I'm happy to share a comprehensive agent code example that beautifully combines transcript logging and call recording for you:
Copy code
from pathlib import Path
import datetime
import logging
from dotenv import load_dotenv
from livekit import api
from livekit.agents import JobContext, WorkerOptions, cli, metrics
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram, silero

load_dotenv(dotenv_path=Path(__file__).parent / '.env')

logger = logging.getLogger("combined-recording-agent")
logger.setLevel(logging.INFO)

async def entrypoint(ctx: JobContext):
    start_time = datetime.datetime.now()
    lkapi = api.LiveKitAPI()
    egress_req = api.RoomCompositeEgressRequest(
        room_name=ctx.room.name,
        preset=api.EncodingOptionsPreset.H264_720P_30,
        audio_only=False,
        file_outputs=[api.EncodedFileOutput(
            filename=f"recording_{ctx.room.name}_{start_time.strftime('%Y%m%d_%H%M%S')}.mp4"
        )],
    )
    egress_info = await lkapi.egress.start_room_composite_egress(egress_req)
    transcripts = []
    session = AgentSession(vad=silero.VAD.load())

    @session.on("user_input_transcribed")
    def on_transcript(transcript):
        if transcript.is_final:
            timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            transcript_entry = f"[{timestamp}] {transcript.transcript}"
            transcripts.append(transcript_entry)
            with open(f"transcripts_{ctx.room.name}.txt", "a") as f:
                f.write(f"{transcript_entry}\n")

    async def finalize_session():
        end_time = datetime.datetime.now()
        duration = end_time - start_time
        with open(f"session_summary_{ctx.room.name}.txt", "w") as f:
            f.write(f"Session started: {start_time}\n")
            f.write(f"Session ended: {end_time}\n")
            f.write(f"Total duration: {duration}\n")
        await lkapi.egress.stop_egress(egress_info.egress_id)
        await lkapi.aclose()

    ctx.add_shutdown_callback(finalize_session)
    await session.start(
        agent=Agent(
            instructions="You are a helpful assistant that transcribes user speech and records the full session.",
            stt=deepgram.STT(),
            vad=silero.VAD.load()
        ),
        room=ctx.room
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here's a quick summary of what this code does: • It starts Egress recording for both audio and video. • Logs real-time transcripts with timestamps, so nothing important gets missed. • Saves a session history and calculates the call duration neatly when the session ends. If you'd like any further customization or have questions, please don't hesitate to reach out—I'm here to help! Sources: Session recording and transcripts | LiveKit Docs | complex-agents/note-taking-assistant/agent.py
s
im using my custom deployment for this so help me out to do that
t
I'd love to understand your custom deployment a bit better so I can assist you more effectively. Could you share a few details with me? • Are you using a specific database, like PostgreSQL or MongoDB, to store your transcripts? • Do you have a favorite spot where you keep your recordings, such as a local server or cloud storage? • Are there any custom APIs or frameworks that you're working with in your deployment? Knowing this will really help me tailor the best solution just for you. Looking forward to your reply!
s
im using my custom deployment i wnst to save the transcript session id room id and userid and transcripts, audio recordings. i need worker code which can be used in custom server
t
I'm happy to share a complete worker code example tailored for your custom deployment. This script takes care of saving the session ID, room ID, user ID, transcripts, and audio recordings for you:
Copy code
import asyncio
import datetime
import json
import os
from pathlib import Path
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram, openai
from livekit import api

load_dotenv()

async def entrypoint(ctx: JobContext):
    session_id = ctx.job.id
    room_id = ctx.room.name
    user_id = None
    for participant in ctx.room.remote_participants.values():
        user_id = participant.identity
        break

    ctx.log_context_fields.update({
        "session_id": session_id,
        "room_id": room_id,
        "user_id": user_id,
        "worker_id": "custom-worker-001"
    })

    egress_client = api.LiveKitAPI(
        url=os.getenv("LIVEKIT_URL"),
        api_key=os.getenv("LIVEKIT_API_KEY"),
        api_secret=os.getenv("LIVEKIT_API_SECRET")
    )

    recording_request = api.RoomCompositeEgressRequest(
        room_name=room_id,
        layout="speaker-dark",
        file=api.EncodedFileOutput(
            file_type=api.EncodedFileType.MP4,
            filepath=f"recordings/{session_id}_{room_id}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4",
            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("S3_BUCKET")
            )
        )
    )

    try:
        egress_info = await egress_client.room_composite_egress.start_room_composite_egress(recording_request)
        print(f"Started recording with ID: {egress_info.egress_id}")
    except Exception as e:
        print(f"Failed to start recording: {e}")

    session = AgentSession()

    @session.on("user_input_transcribed")
    def on_transcript(transcript):
        if transcript.is_final:
            timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            transcript_data = {
                "session_id": session_id,
                "room_id": room_id,
                "user_id": user_id,
                "timestamp": timestamp,
                "transcript": transcript.transcript,
                "is_final": transcript.is_final
            }
            transcript_file = f"transcripts/{session_id}_{room_id}_transcripts.jsonl"
            os.makedirs(os.path.dirname(transcript_file), exist_ok=True)
            with open(transcript_file, "a") as f:
                f.write(json.dumps(transcript_data) + "\n")

    def save_session_data():
        session_data = {
            "session_id": session_id,
            "room_id": room_id,
            "user_id": user_id,
            "start_time": datetime.datetime.now().isoformat(),
            "conversation_history": []
        }
        if hasattr(session, 'history'):
            for item in session.history:
                session_data["conversation_history"].append({
                    "role": item.role if hasattr(item, 'role') else "unknown",
                    "content": item.text_content if hasattr(item, 'text_content') else str(item),
                    "timestamp": datetime.datetime.now().isoformat()
                })
        session_file = f"sessions/{session_id}_{room_id}_session.json"
        os.makedirs(os.path.dirname(session_file), exist_ok=True)
        with open(session_file, "w") as f:
            json.dump(session_data, f, indent=2)
        print(f"Session data saved to {session_file}")

    ctx.add_shutdown_callback(save_session_data)

    await session.start(
        agent=Agent(
            instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
            stt=deepgram.STT(),
            llm=openai.LLM(),
            tts=openai.TTS()
        ),
        room=ctx.room
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s what this code does for you: • It saves the session ID, room ID, user ID, and transcripts neatly in JSON format. • It kicks off audio/video recording using Egress and safely stores the files in S3 or your local directory. • It thoughtfully preserves the full session history when the session shuts down. If you’d like me to walk you through any part of this or need it adjusted to fit your needs better, just let me know — I’m here to help! Sources: Job lifecycle | LiveKit Docs | Session recording and transcripts | LiveKit Docs | pipeline-stt/transcriber/transcriber.py
s
i need transcripts directly to my database
t
Could you please share which database you’re using (like PostgreSQL, MongoDB, MySQL)? Also, if you have a preferred schema or table structure for storing the transcripts—maybe including fields like session ID, room ID, user ID, timestamp, and the transcript text—I'd love to hear about it! This will help me assist you better.
s
i need to save it in postgress db
t
I'd love to help you save transcripts directly to a PostgreSQL database! You can use the
asyncpg
library for asynchronous database operations. Here’s an updated example that shows how to save transcripts directly to PostgreSQL:
Copy code
import asyncio
import datetime
import os
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram
import asyncpg

load_dotenv()

async def entrypoint(ctx: JobContext):
    session_id = ctx.job.id
    room_id = ctx.room.name
    user_id = None
    for participant in ctx.room.remote_participants.values():
        user_id = participant.identity
        break

    # Connect to PostgreSQL database
    db_pool = await asyncpg.create_pool(
        user=os.getenv("POSTGRES_USER"),
        password=os.getenv("POSTGRES_PASSWORD"),
        database=os.getenv("POSTGRES_DB"),
        host=os.getenv("POSTGRES_HOST"),
        port=os.getenv("POSTGRES_PORT")
    )

    # Ensure the table exists
    async with db_pool.acquire() as conn:
        await conn.execute('''
            CREATE TABLE IF NOT EXISTS transcripts (
                id SERIAL PRIMARY KEY,
                session_id TEXT,
                room_id TEXT,
                user_id TEXT,
                timestamp TIMESTAMP,
                transcript TEXT
            )
        ''')

    session = AgentSession()

    @session.on("user_input_transcribed")
    async def on_transcript(transcript):
        if transcript.is_final:
            timestamp = datetime.datetime.now()
            async with db_pool.acquire() as conn:
                await conn.execute('''
                    INSERT INTO transcripts (session_id, room_id, user_id, timestamp, transcript)
                    VALUES ($1, $2, $3, $4, $5)
                ''', session_id, room_id, user_id, timestamp, transcript.transcript)

    async def finalize_session():
        await db_pool.close()

    ctx.add_shutdown_callback(finalize_session)

    await session.start(
        agent=Agent(
            instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
            stt=deepgram.STT()
        ),
        room=ctx.room
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s what this code does for you: • It connects to your PostgreSQL database using
asyncpg
, making things efficient and asynchronous. • It creates a
transcripts
table if it’s not already there, so you don’t have to worry about setup. • Whenever a final transcript is ready, it inserts it into the database along with session ID, room ID, user ID, timestamp, and the transcript text. Just make sure you have these environment variables set up properly:
Copy code
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=your_db_name
POSTGRES_HOST=your_db_host
POSTGRES_PORT=your_db_port
If you run into any issues or want me to help tweak this further, please don’t hesitate to reach out. I’m here to support you every step of the way!
s
i beed user and agent transcript in a list and at the ending of session i need to save it in postgress, save recording locally
t
I've put together an updated example for you that gently collects user and agent transcripts in a list throughout the session and then saves them to PostgreSQL once the session wraps up. Plus, it saves the recording locally for your convenience:
Copy code
import asyncio
import datetime
import os
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram
from livekit import api
import asyncpg

load_dotenv()

async def entrypoint(ctx: JobContext):
    session_id = ctx.job.id
    room_id = ctx.room.name
    user_id = None
    for participant in ctx.room.remote_participants.values():
        user_id = participant.identity
        break

    # Connect to PostgreSQL database
    db_pool = await asyncpg.create_pool(
        user=os.getenv("POSTGRES_USER"),
        password=os.getenv("POSTGRES_PASSWORD"),
        database=os.getenv("POSTGRES_DB"),
        host=os.getenv("POSTGRES_HOST"),
        port=os.getenv("POSTGRES_PORT")
    )

    # Ensure the table exists
    async with db_pool.acquire() as conn:
        await conn.execute('''
            CREATE TABLE IF NOT EXISTS session_transcripts (
                id SERIAL PRIMARY KEY,
                session_id TEXT,
                room_id TEXT,
                user_id TEXT,
                transcripts JSONB,
                recording_path TEXT
            )
        ''')

    # Initialize transcript storage
    transcripts = []

    # Start local recording using Egress
    egress_client = api.LiveKitAPI(
        url=os.getenv("LIVEKIT_URL"),
        api_key=os.getenv("LIVEKIT_API_KEY"),
        api_secret=os.getenv("LIVEKIT_API_SECRET")
    )

    recording_path = f"recordings/{session_id}_{room_id}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
    recording_request = api.RoomCompositeEgressRequest(
        room_name=room_id,
        layout="speaker-dark",
        file=api.EncodedFileOutput(
            file_type=api.EncodedFileType.MP4,
            filepath=recording_path
        )
    )

    try:
        egress_info = await egress_client.room_composite_egress.start_room_composite_egress(recording_request)
        print(f"Started recording with ID: {egress_info.egress_id}")
    except Exception as e:
        print(f"Failed to start recording: {e}")

    session = AgentSession()

    @session.on("user_input_transcribed")
    def on_user_transcript(transcript):
        if transcript.is_final:
            transcripts.append({
                "role": "user",
                "timestamp": datetime.datetime.now().isoformat(),
                "text": transcript.transcript
            })

    @session.on("agent_output_generated")
    def on_agent_transcript(output):
        transcripts.append({
            "role": "agent",
            "timestamp": datetime.datetime.now().isoformat(),
            "text": output.text
        })

    async def finalize_session():
        # Save transcripts and recording path to PostgreSQL
        async with db_pool.acquire() as conn:
            await conn.execute('''
                INSERT INTO session_transcripts (session_id, room_id, user_id, transcripts, recording_path)
                VALUES ($1, $2, $3, $4, $5)
            ''', session_id, room_id, user_id, transcripts, recording_path)

        # Stop Egress recording
        try:
            await egress_client.room_composite_egress.stop_egress(egress_info.egress_id)
            print(f"Stopped recording with ID: {egress_info.egress_id}")
        except Exception as e:
            print(f"Failed to stop recording: {e}")

        await db_pool.close()

    ctx.add_shutdown_callback(finalize_session)

    await session.start(
        agent=Agent(
            instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
            stt=deepgram.STT()
        ),
        room=ctx.room
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s a quick summary of what this code does: • Gathers user and agent transcripts in a list as the session goes on. • At the end of the session, it saves those transcripts along with the recording path into a PostgreSQL database. • Keeps a local copy of the recording in the
recordings
folder. Just a gentle reminder to make sure you’ve set these environment variables before running the code:
Copy code
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=your_db_name
POSTGRES_HOST=your_db_host
POSTGRES_PORT=your_db_port
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
If you have any questions or need me to walk you through any part of this, please don’t hesitate to ask. I’m here to help!
s
update the code, i need to use uri of postgress db instead of username host pass
t
I'm glad to share the updated code that now uses a PostgreSQL URI for the database connection instead of separate username, host, and password variables. This should make things a bit smoother for you:
Copy code
import asyncio
import datetime
import os
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram
from livekit import api
import asyncpg

load_dotenv()

async def entrypoint(ctx: JobContext):
    session_id = ctx.job.id
    room_id = ctx.room.name
    user_id = None
    for participant in ctx.room.remote_participants.values():
        user_id = participant.identity
        break

    # Connect to PostgreSQL database using URI
    db_uri = os.getenv("POSTGRES_URI")
    db_pool = await asyncpg.create_pool(dsn=db_uri)

    # Ensure the table exists
    async with db_pool.acquire() as conn:
        await conn.execute('''
            CREATE TABLE IF NOT EXISTS session_transcripts (
                id SERIAL PRIMARY KEY,
                session_id TEXT,
                room_id TEXT,
                user_id TEXT,
                transcripts JSONB,
                recording_path TEXT
            )
        ''')

    # Initialize transcript storage
    transcripts = []

    # Start local recording using Egress
    egress_client = api.LiveKitAPI(
        url=os.getenv("LIVEKIT_URL"),
        api_key=os.getenv("LIVEKIT_API_KEY"),
        api_secret=os.getenv("LIVEKIT_API_SECRET")
    )

    recording_path = f"recordings/{session_id}_{room_id}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
    recording_request = api.RoomCompositeEgressRequest(
        room_name=room_id,
        layout="speaker-dark",
        file=api.EncodedFileOutput(
            file_type=api.EncodedFileType.MP4,
            filepath=recording_path
        )
    )

    try:
        egress_info = await egress_client.room_composite_egress.start_room_composite_egress(recording_request)
        print(f"Started recording with ID: {egress_info.egress_id}")
    except Exception as e:
        print(f"Failed to start recording: {e}")

    session = AgentSession()

    @session.on("user_input_transcribed")
    def on_user_transcript(transcript):
        if transcript.is_final:
            transcripts.append({
                "role": "user",
                "timestamp": datetime.datetime.now().isoformat(),
                "text": transcript.transcript
            })

    @session.on("agent_output_generated")
    def on_agent_transcript(output):
        transcripts.append({
            "role": "agent",
            "timestamp": datetime.datetime.now().isoformat(),
            "text": output.text
        })

    async def finalize_session():
        # Save transcripts and recording path to PostgreSQL
        async with db_pool.acquire() as conn:
            await conn.execute('''
                INSERT INTO session_transcripts (session_id, room_id, user_id, transcripts, recording_path)
                VALUES ($1, $2, $3, $4, $5)
            ''', session_id, room_id, user_id, transcripts, recording_path)

        # Stop Egress recording
        try:
            await egress_client.room_composite_egress.stop_egress(egress_info.egress_id)
            print(f"Stopped recording with ID: {egress_info.egress_id}")
        except Exception as e:
            print(f"Failed to stop recording: {e}")

        await db_pool.close()

    ctx.add_shutdown_callback(finalize_session)

    await session.start(
        agent=Agent(
            instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
            stt=deepgram.STT()
        ),
        room=ctx.room
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s a quick summary of what this code does: • It uses the
POSTGRES_URI
environment variable to connect to your PostgreSQL database, making the setup cleaner. • It keeps the functionality to save transcripts and the recording path to your database when the session ends. • The recordings are saved locally in the
recordings
folder for easy access. Just a gentle reminder to make sure you have these environment variables set up correctly:
Copy code
POSTGRES_URI=postgresql://user:password@host:port/database
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
If you have any questions or need me to walk you through any part of this, please don’t hesitate to ask. I’m here to help!
r
what if we don't want to use the engress cloud recorder, we'd want to record locally to an mp4 file - just like pipecat
t
I'm happy to help you with recording locally to an MP4 file without using Egress by taking advantage of client-side recording features. Depending on your platform, here are some friendly options for you: • Android: You can use the
VideoFileRenderer
along with
MediaCodec
and
MediaMuxer
to save local audio and video tracks directly into an MP4 file. This approach is nicely showcased in LiveKit's Android sample app. • Web: The
LocalTrackRecorder
class in the LiveKit JS SDK is a great tool here. It wraps the browser's
MediaRecorder
API, allowing you to record local tracks into MP4 or WebM files with ease. • iOS/Desktop: For iOS and macOS, you might want to explore native media APIs like
AVAssetWriter
and
AVCaptureSession
. On desktop platforms, FFmpeg-based solutions can be very effective. These options let you record the local participant’s audio and video right on your device. If you let me know which platform you’re working with, I’d be delighted to share some specific code examples or guide you further! Sources: README.md | Recording and export | LiveKit docs | sample-app-record-local/README.md | src/room/track/record.ts
r
No understand, im using livekit cloud but i don't want to use the engress recorder since its only 60mins on the free plan - my usage is so small, i don't want to upgrade, i need a way to locally record the meeting in mp4 without using the cloud recorder
t
I'd be happy to help you record meetings locally in MP4 format without using the LiveKit Egress recorder. You can achieve this by implementing client-side recording directly on the participant's device. Here's a friendly overview of how you might do this: • Web (JavaScript/TypeScript): You can use the
MediaRecorder
API to capture local audio and video tracks. This way, the recording can be saved directly to the user's device as an MP4 or WebM file. • Android: Using
VideoFileRenderer
along with
MediaCodec
and
MediaMuxer
allows you to record local tracks into an MP4 file. • iOS/Desktop: Native media APIs like
AVAssetWriter
and
AVCaptureSession
are great tools to capture and save local tracks. Keep in mind, these methods record only the local participant's audio and video. If you'd like to include remote participants, you can subscribe to their tracks and mix them locally before recording. Feel free to share your target platform with me—I’d love to provide you with specific code examples or any further guidance you might need!
r
yes, how would i go about this, im using the react sdk of livekit - give me the full code
t
I'm happy to share a complete React component example that helps you record locally in MP4 format using the LiveKit React SDK and the MediaRecorder API. Take a look:
Copy code
`import React, { useState, useCallback, useRef } from 'react';
import { useLocalParticipant, useRoomContext } from '@livekit/components-react';
import { LocalVideoTrack, isRecordingSupported } from 'livekit-client';

const LocalRecorder: React.FC = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordedBlob, setRecordedBlob] = useState<blob |="" null="">(null);
  const [mimeType, setMimeType] = useState<string>(&#39;&#39;);
  const { localParticipant } = useLocalParticipant();
  const room = useRoomContext();
  const recordingTrackRef = useRef<localvideotrack |="" null="">(null);

  const startRecording = useCallback(async () => {
    if (!isRecordingSupported()) {
      console.error(&#39;MediaRecorder is not supported in this browser&#39;);
      return;
    }

    const videoTrack = localParticipant.getTrackPublication(&#39;camera&#39;)?.track as LocalVideoTrack;
    if (!videoTrack) {
      console.error(&#39;No local video track found&#39;);
      return;
    }

    recordingTrackRef.current = videoTrack;
    videoTrack.startPreConnectBuffer(100);
    setIsRecording(true);

    const recordingMimeType = videoTrack.getPreConnectBufferMimeType();
    setMimeType(recordingMimeType || &#39;video/mp4&#39;);
    console.log(`Recording started with MIME type: ${recordingMimeType}`);
  }, [localParticipant]);

  const stopRecording = useCallback(async () => {
    const videoTrack = recordingTrackRef.current;
    if (!videoTrack) return;

    const stream = videoTrack.getPreConnectBuffer();
    const finalMimeType = videoTrack.getPreConnectBufferMimeType() || &#39;video/mp4&#39;;

    videoTrack.stopPreConnectBuffer();
    setIsRecording(false);

    if (stream) {
      const chunks: Uint8Array[] = [];
      const reader = stream.getReader();

      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          chunks.push(value);
        }

        const recordedBlob = new Blob(chunks, { type: finalMimeType });
        setRecordedBlob(recordedBlob);
        console.log(`Recording completed. Size: ${recordedBlob.size} bytes, Type: ${finalMimeType}`);
      } catch (error) {
        console.error(&#39;Error reading recorded stream:&#39;, error);
      } finally {
        reader.releaseLock();
      }
    }

    recordingTrackRef.current = null;
  }, []);

  const downloadRecording = useCallback(() => {
    if (!recordedBlob) return;

    const url = URL.createObjectURL(recordedBlob);
    const a = document.createElement(&#39;a&#39;);
    a.href = url;
    a.download = `recording-${Date.now()}.${mimeType.includes(&#39;mp4&#39;) ? &#39;mp4&#39; : &#39;webm&#39;}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, [recordedBlob, mimeType]);

  return (
    <div>
      <div>
        <button onclick="{startRecording}" disabled="{isRecording" ||="" !isrecordingsupported()}="">
          {isRecording ? &#39;Recording...&#39; : &#39;Start Recording&#39;}
        </button>
        <button onclick="{stopRecording}" disabled="{!isRecording}">
          Stop Recording
        </button>
      </div>

      {mimeType && <p>Recording format: {mimeType}</p>}

      {recordedBlob && (
        <div>
          <p>Recording ready! Size: {(recordedBlob.size / 1024 / 1024).toFixed(2)} MB</p>
          <button onclick="{downloadRecording}">Download Recording</button>
        </div>
      )}

      {!isRecordingSupported() && (
        <p style="{{" color:="" 'red'="" }}="">MediaRecorder is not supported in this browser</p>
      )}
    </div>
  );
};

export default LocalRecorder;</code></pre><br/><p>This component is designed to:</p><ul><li>Start and stop recording smoothly using the <code>MediaRecorder</code> API.</li><li>Handle your recorded data as a Blob and give you the option to download it as an MP4 file.</li><li>Check if your browser supports recording with <code>isRecordingSupported()</code> so you know if it will work.</li></ul><br/><p>If you have any questions or need help tweaking this to better fit your needs, just let me know! I’m here to help you through it.</p>`
Sources: src/room/track/LocalTrack.ts | README.md