i
hi
t
Thanks for reaching out, Raj. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — how can I help today? What are you trying to do with LiveKit (bug, integration, account/billing, docs, or something else)? Please share any error messages, room IDs, SDK/language, and steps to reproduce if it’s a technical issue.
i
i have a question like since im using videoconference can i use the microphone control bar to pass pcm audio into a websocket
t
You're asking whether the microphone control bar in a LiveKit videoconference can be used to pass PCM audio into a WebSocket. Short answer: yes — but not via the UI control bar alone. You’ll need to use the SDK or LiveKit egress. Options you can use • Client-side (SDK): Subscribe to your local audio track, use LiveKit’s
AudioStream
(or equivalent in your SDK) to access raw PCM frames, and send those bytes over your own WebSocket connection. Example flow: a. Get the local audio track. b. Create an
AudioStream
from the track and iterate frames. c. Send
frame.data
(PCM, typically int16) over your WebSocket. • Server-side (Track Egress): Use LiveKit Track Egress to stream raw PCM (
pcm_s16le
) for a participant’s track directly to a WebSocket endpoint. This is ideal for real-time processing at scale (transcription, analysis). Questions so I can give exact guidance • Which SDK/language are you using (JS, Swift, Android, Rust, Python, etc.)? • Do you want client-side (in-browser/app) capture or server-side egress to a WebSocket? • Do you need sample rate conversion or specific PCM format (int16, 48kHz, mono/stereo)? Tell me the SDK and preferred approach and I’ll provide a concise code example for your setup. Sources: Camera & microphone | LiveKit docs | Capturing the First Few Seconds of a Call for Processing | Track egress | LiveKit docs | Universal Egress | Swift quickstart | LiveKit docs
i
okay my question was let say i have implemented the <videoconference/> react component which provides the microphone for audio input to others now how can i use it to publish this audio to others in the room or send the audio in websocket since i dont want to create another mic button and send audio pcm chunks
t
You're asking how to reuse the microphone already exposed by your <videoconference/> React component so it continues publishing to the room while also sending raw PCM to a WebSocket — without adding another mic button. You can do this by grabbing the existing local audio track and tapping its raw frames, then streaming those bytes over a WebSocket. Which approach do you want? • Client-side: use the existing local
AudioTrack
and an `AudioStream`/processor in the LiveKit JS SDK to read PCM frames and send them over a WebSocket (keeps one mic control). • Server-side: use Track Egress to stream a participant’s track (PCM) directly to a WebSocket from the backend (no client changes, scales better). If you want the client-side code example for React/JS, tell me which LiveKit JS SDK version you’re using (or I can give a current JS example). If you prefer Track Egress, tell me whether you control the backend so I can show the egress request shape.
i
client-side i want to do since my WebSocket is in client side
t
You're using the existing microphone from your <videoconference/> React component and want to continue publishing to the room while also sending raw PCM to a client-side WebSocket — without adding another mic button. Here's a concise client-side approach and a React/JS example. Plan • Reuse the existing local audio track that your videoconference component already publishes. • Create an audio processor/stream from that track to read raw PCM frames. • Open a WebSocket and send each PCM frame (typically int16 PCM at 48kHz) as binary. • Keep the original published track unchanged so the room still receives audio. Minimal React/JS example (LiveKit JS) 1. Get the local audio track published by your component (you should have access to the LocalParticipant or the published track). 2. Use an AudioWorklet/MediaStreamTrackProcessor or LiveKit’s AudioStream utility (if available in your SDK) to read frames. 3. Send frames over WebSocket. Example using MediaStreamTrackProcessor (works in modern browsers):
Copy code
// assume `localAudioTrack` is the LocalAudioTrack instance your component created/published
// and `trackMediaStreamTrack` is the underlying MediaStreamTrack
const trackMediaStreamTrack = localAudioTrack.mediaStreamTrack; // adapt to how your SDK exposes it

// create processor to read raw audio frames
const processor = new MediaStreamTrackProcessor({ track: trackMediaStreamTrack });
const reader = processor.readable.getReader();

// open websocket
const ws = new WebSocket("wss://your-server.example");
ws.binaryType = "arraybuffer";

(async function readLoop(){
  while (true) {
    const { value: audioFrame, done } = await reader.read();
    if (done) break;
    // audioFrame is an AudioData object (Float32 PCM)
    // convert Float32 -> Int16 PCM
    const float32 = new Float32Array(audioFrame.allocationSize ? audioFrame.allocationSize/4 : audioFrame.numberOfFrames * audioFrame.numberOfChannels);
    audioFrame.copyTo(float32);
    audioFrame.close();

    // convert to int16 little-endian
    const int16 = new Int16Array(float32.length);
    for (let i = 0; i < float32.length; i++) {
      let s = Math.max(-1, Math.min(1, float32[i]));
      int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
    }

    // send as ArrayBuffer
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(int16.buffer);
    }
  }
})();
Notes and important details • The processor reads the same microphone source your component publishes — no extra mic UI required. • Browser support: MediaStreamTrackProcessor and AudioData are modern web APIs; if you need older browser support, use an AudioWorklet or the SDK’s
AudioStream
helper if provided. • PCM format: above converts to 16-bit little-endian PCM. Confirm your server expects that format and sample rate (commonly 48kHz). Do any resampling on client if needed. • Performance: sending every frame can be high-frequency; consider batching frames or using a worker to avoid blocking the main thread. • If your SDK exposes a higher-level
AudioStream
that yields frames directly (PCM int16), use that to avoid manual conversion. If you want, tell me: • which LiveKit JS SDK version you’re using (or whether you prefer LiveKit’s
AudioStream
), and • the PCM format your WebSocket server expects (int16/float32, sample rate, mono/stereo) I’ll provide a tailored snippet (AudioStream-based or an AudioWorklet example) and suggestions for batching/resampling.
i
import type { RoomOptions } from 'livekit-client'; import { LiveKitRoom, RoomAudioRenderer, VideoConference, useRoomContext } from '@alert-easter-19258/components-react';
t
You're using the LiveKit React components. Below is a concise TypeScript React example that shows how to grab the existing local audio track from useRoomContext, create a MediaStreamTrackProcessor to get PCM frames, convert Float32 -> int16 PCM, and send binary frames over a client-side WebSocket — all while keeping the track published to the room (no extra mic button). Key points • Uses the already-published local audio track from LocalParticipant. • Uses MediaStreamTrackProcessor (modern browsers). If you need older-browser support, I can provide an AudioWorklet version or use LiveKit's AudioStream helper. • Sends 16-bit little-endian PCM (int16) at the track sample rate (typically 48kHz). Adjust if your server expects a different format or sample rate. • Consider batching frames in production to reduce send frequency. Example (React + TypeScript)
Copy code
import React, { useEffect, useRef } from "react";
import { useRoomContext } from "@livekit/components-react";
import type { LocalAudioTrack } from "livekit-client";

export function WebSocketAudioForwarder({ wsUrl }: { wsUrl: string }) {
  const { room } = useRoomContext();
  const wsRef = useRef<WebSocket | null>(null);
  const readerRef = useRef<ReadableStreamDefaultReader<AudioData> | null>(null);

  useEffect(() => {
    if (!room) return;

    // open websocket
    wsRef.current = new WebSocket(wsUrl);
    wsRef.current.binaryType = "arraybuffer";

    // find local audio track published by the component
    const localParticipant = room.localParticipant;
    const publishedTracks = Array.from(localParticipant.audioTracks.values());
    if (publishedTracks.length === 0) return;

    // adapt depending on LiveKit LocalAudioTrack shape
    const localTrackPublication = publishedTracks[0]; // pick the first audio track
    const localTrack = localTrackPublication.track as LocalAudioTrack | null;
    if (!localTrack) return;

    // get underlying MediaStreamTrack
    const mediaTrack = (localTrack.mediaStreamTrack as MediaStreamTrack) || null;
    if (!mediaTrack) return;

    // create MediaStreamTrackProcessor to read AudioData frames
    // @ts-ignore - types for MediaStreamTrackProcessor may be missing in some TS libs
    const processor = new (window as any).MediaStreamTrackProcessor({ track: mediaTrack });
    const reader = processor.readable.getReader();
    readerRef.current = reader;

    let cancelled = false;
    (async () => {
      while (!cancelled) {
        const result = await reader.read();
        if (result.done) break;
        const audioData: AudioData = result.value;

        // copy Float32 PCM samples
        const channels = audioData.numberOfChannels;
        const frames = audioData.numberOfFrames;
        const floatBuf = new Float32Array(frames * channels);
        audioData.copyTo(floatBuf);
        audioData.close();

        // convert Float32 -> Int16 little-endian
        const int16 = new Int16Array(floatBuf.length);
        for (let i = 0; i < floatBuf.length; i++) {
          let s = Math.max(-1, Math.min(1, floatBuf[i]));
          int16[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
        }

        // optionally batch frames here before sending
        if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
          wsRef.current.send(int16.buffer);
        }
      }
    })();

    // cleanup on unmount
    return () => {
      cancelled = true;
      readerRef.current?.cancel().catch(() => {});
      processor?.readable?.cancel?.();
      wsRef.current?.close();
      readerRef.current = null;
      wsRef.current = null;
    };
  }, [room, wsUrl]);

  return null;
}
If you want: • an example using LiveKit's
AudioStream
helper (if present in your SDK), • an AudioWorklet version for broader browser support, • batching/resampling guidance, tell me which you prefer and the PCM format/sample rate your WebSocket server expects.
i
is piece of code provides pcm?
t
Short answer: Yes — the React/TS example I gave sends PCM to the WebSocket after converting browser AudioData (Float32) into 16-bit little-endian PCM (Int16). Clarifications: • The code reads AudioData frames from the existing published MediaStreamTrack via MediaStreamTrackProcessor. • It copies Float32 samples, converts them to int16, and sends the Int16Array buffer over the WebSocket — that buffer is 16-bit PCM little-endian. • Sample rate and channel layout remain as provided by the track (typically 48 kHz, stereo). If your server expects a different sample rate or mono, you must resample or mix channels before sending. If you want, I can: • Provide an example that sends Float32 PCM instead of Int16. • Add resampling/mixing code or batching for performance. Which would you prefer?
i
which one is better like using livkit react microphone audio or direct audio from mic?
t
Good question — here’s a concise comparison and my recommendation. Using the LiveKit React microphone (the track your <VideoConference/> already publishes) • Pros: ◦ Single source: the audio you forward to the WebSocket is exactly the same audio other participants hear (no sync issues). ◦ No extra mic permission prompt or UI needed. ◦ Easier integration: you can tap the published LocalAudioTrack (MediaStreamTrack) and use MediaStreamTrackProcessor / AudioStream to read frames. ◦ Less code to keep in sync with the conference state (mute/unmute, device changes). • Cons: ◦ Less control before the track is published (you’d need extra processing if you want to modify audio pre-publish). Direct mic capture (navigator.mediaDevices.getUserMedia) • Pros: ◦ Full control: you can process, resample, mix, or encode before publishing or sending. ◦ Useful if you need a custom audio pipeline that differs from what you publish. • Cons: ◦ Duplicate permission and device handling; you must publish a second track to LiveKit or replace the LiveKit track to keep participants hearing the same audio. ◦ Extra complexity to keep the two streams (WebSocket and LiveKit) synchronized and to handle mute/device switching. Recommendation • Use the existing LiveKit React microphone track in almost all cases where you want to both publish to the room and forward PCM to a WebSocket. It’s simpler, avoids duplicate permissions, and guarantees the same audio is sent to both destinations. • Use direct mic capture only if you need pre-publish processing that must not affect what others hear, or you require a completely custom pipeline. If you want, I can provide: • A LiveKit-React snippet (AudioStream or MediaStreamTrackProcessor) to forward PCM (int16/float32) to your WebSocket, or • A pattern for capturing once and publishing both to LiveKit and your WS (if you choose direct capture). Which would you like?
i
actually the issue im facing is liveavatar's avatar is joining the room and from their api im getting one websocket url which they are mentioning i need to provide event data for input audio
t
You can forward the existing LiveKit microphone audio to the LiveAvatar WebSocket from the browser without adding another mic button. Below is a concise React/TypeScript pattern that: • reuses the LocalParticipant’s published microphone MediaStreamTrack (so the same audio goes to the room), • reads raw audio in the browser, converts to 16-bit little-endian PCM (pcm_s16le), and • sends binary frames and mute/unmute events to the LiveAvatar WebSocket URL they gave you. Use this when LiveAvatar expects pcm_s16le (48kHz commonly). If LiveAvatar expects a different format, tell me and I’ll show resampling/format changes. Example (React + TypeScript — Web Audio API approach):
Copy code
import { useEffect, useRef } from "react";
import { useRoomContext } from "@livekit/components-react";
import type { LocalAudioTrack } from "livekit-client";

export function ForwardMicToLiveAvatar({ wsUrl }: { wsUrl: string }) {
  const { room } = useRoomContext();
  const wsRef = useRef<WebSocket | null>(null);
  const audioContextRef = useRef<AudioContext | null>(null);
  const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
  const processorRef = useRef<ScriptProcessorNode | null>(null);

  useEffect(() => {
    if (!room || !wsUrl) return;

    // find local microphone track
    const localParticipant = room.localParticipant;
    const published = Array.from(localParticipant.audioTracks.values());
    const pub = published.find(p => p.track?.source === "microphone");
    const localTrack = pub?.track as LocalAudioTrack | undefined;
    if (!localTrack) return;

    const mediaTrack = localTrack.mediaStreamTrack as MediaStreamTrack;
    const mediaStream = new MediaStream([mediaTrack]);

    // open websocket
    wsRef.current = new WebSocket(wsUrl);
    wsRef.current.binaryType = "arraybuffer";

    // setup AudioContext + ScriptProcessorNode for raw audio
    const AudioCtx = window.AudioContext || (window as any).webkitAudioContext;
    const ac = new AudioCtx();
    audioContextRef.current = ac;
    const src = ac.createMediaStreamSource(mediaStream);
    sourceRef.current = src;

    // buffer size 4096, 1 input, 1 output (mono). Adjust to needs.
    const proc = ac.createScriptProcessor(4096, 1, 1);
    processorRef.current = proc;

    src.connect(proc);
    // optional: keep connected to destination so audio continues to play through output
    proc.connect(ac.destination);

    // handle mic mute/unmute to send event messages
    const sendMuteEvent = (muted: boolean) => {
      try {
        wsRef.current?.send(JSON.stringify({ muted }));
      } catch (e) {}
    };
    localTrack.on?.("muted", () => sendMuteEvent(true));
    localTrack.on?.("unmuted", () => sendMuteEvent(false));

    proc.onaudioprocess = (ev: AudioProcessingEvent) => {
      if (wsRef.current?.readyState !== WebSocket.OPEN) return;
      const input = ev.inputBuffer.getChannelData(0); // mono channel
      const samples = input.length;
      const out = new Int16Array(samples);
      for (let i = 0; i < samples; i++) {
        let s = Math.max(-1, Math.min(1, input[i]));
        out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
      }
      wsRef.current.send(out.buffer);
    };

    return () => {
      // cleanup
      try { localTrack.off?.("muted"); localTrack.off?.("unmuted"); } catch {}
      processorRef.current?.disconnect();
      sourceRef.current?.disconnect();
      audioContextRef.current?.close().catch(() => {});
      wsRef.current?.close();
      processorRef.current = null;
      sourceRef.current = null;
      audioContextRef.current = null;
      wsRef.current = null;
    };
  }, [room, wsUrl]);

  return null;
}
Quick notes: • The code sends pcm_s16le binary buffers. LiveAvatar’s WebSocket commonly expects this; confirm sample rate/channel (LiveKit audio is typically 48kHz). • Use mono mixing (above uses channel 0). If LiveAvatar expects mono and your track is stereo, mix channels or request only one channel. • MediaStreamTrackProcessor is an alternative if you prefer modern API and want access to AudioData frames; ScriptProcessorNode has wider support but is deprecated in some contexts. • Batch frames or use a Worker for heavy loads to avoid blocking the main thread. Do you want: • a MediaStreamTrackProcessor example instead, or • help adapting this to a specific LiveAvatar event schema (e.g., they require initial handshake JSON or specific mute message format)? Sources: Universal Egress | Universal Egress | Universal Egress | Track egress | LiveKit docs | Recording and export | LiveKit docs
i
const defaultCapture = DEFAULT_ROOM_OPTIONS.videoCaptureDefaults ?? {}; const overrideCapture = overrides.videoCaptureDefaults ?? {}; merged.videoCaptureDefaults = { ...defaultCapture, ...overrideCapture, resolution: { width: overrideCapture.resolution?.width ?? defaultCapture.resolution?.width ?? 1280, height: overrideCapture.resolution?.height ?? defaultCapture.resolution?.height ?? 720, }, }; return merged; } type ActiveRoomLayoutProps = { hostLabel: string; roomName?: string; statusMessage?: string; errorMessage?: string | null; onFinalizeEnd: () => void; }; function ActiveRoomLayout({ hostLabel, roomName, statusMessage, errorMessage, onFinalizeEnd }: ActiveRoomLayoutProps) { // const room = useRoomContext(); return ( <div style={{ flex: 1, display: 'grid', gridTemplateRows: 'auto 1fr', }} > <header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '1rem 1.5rem', borderBottom: '1px solid rgba(148, 163, 184, 0.25)', background: 'rgba(15, 23, 42, 0.75)', backdropFilter: 'blur(12px)', color: '#E2E8F0', }} > <div> <p style={{ margin: 0, fontSize: '0.8rem', letterSpacing: '0.08em', textTransform: 'uppercase', color: '#38BDF8' }}>{hostLabel}</p> <h2 style={{ margin: '0.35rem 0 0', fontSize: '1.4rem', fontWeight: 600, color: '#F8FAFC' }}>{roomName ?? 'Live Interview Room'}</h2> </div> <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}> {statusMessage && ( <span style={{ fontSize: '0.9rem', color: '#94A3B8' }}>{statusMessage}</span> )} </div> </header> <div style={{ position: 'relative', flex: 1, background: '#0F172A', display: 'flex', }} > <VideoConference /> {errorMessage && ( <div role="alert" style={{ position: 'absolute', bottom: '1.5rem', left: '50%', transform: 'translateX(-50%)', padding: '0.85rem 1rem', borderRadius: '0.9rem', background: 'rgba(248, 113, 113, 0.15)', border: '1px solid rgba(248, 113, 113, 0.35)', color: '#FECACA', fontSize: '0.9rem', lineHeight: 1.45, backdropFilter: 'blur(8px)', }} > {errorMessage} </div> )} </div> </div> ); } export default function LiveKitMeet({ //!working token, serverUrl, roomName, hostLabel = 'Live Avatar Team', statusMessage, errorMessage, isSettingUp = false, onSetupRoom, onEndCall, roomOptions, children, }: LiveKitMeetProps) { const resolvedRoomOptions = useMemo(() => buildRoomOptions(roomOptions), [roomOptions]); const credentialsReady = Boolean(token && serverUrl); const preJoinStatus = statusMessage ?? 'Trigger room setup to receive LiveKit credentials.'; const [hasEnded, setHasEnded] = useState(false); const finalizeEnd = () => { setHasEnded(true); onEndCall?.(); }; if (hasEnded) { return ( <div data-lk-theme="default" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: 'radial-gradient(circle at top, rgba(15, 23, 42, 0.9), #020617)', color: '#E2E8F0', padding: '2.5rem', textAlign: 'center', }} > <div style={{ maxWidth: 520, padding: '2.4rem', borderRadius: '1.4rem', background: 'rgba(15, 23, 42, 0.85)', border: '1px solid rgba(148, 163, 184, 0.25)', boxShadow: '0 30px 80px rgba(15, 23, 42, 0.55)', backdropFilter: 'blur(16px)', }} > <p style={{ margin: 0, fontSize: '0.82rem', letterSpacing: '0.08em', textTransform: 'uppercase', color: '#38BDF8' }}>Interview complete</p> <h1 style={{ marginTop: '0.85rem', marginBottom: '0.6rem', fontSize: '2.15rem', fontWeight: 600, color: '#F8FAFC' }}>Your interview has finished</h1> <p style={{ marginBottom: '1.5rem', color: '#CBD5F5', lineHeight: 1.6 }}> Thanks for spending time in the room. You can close this window or return to the control panel to review outcomes. </p> {onEndCall && ( <button type="button" onClick={onEndCall} style={{ padding: '0.75rem 1.4rem', borderRadius: '999px', border: 'none', background: 'linear-gradient(135deg, #38BDF8, #6366F1)', color: '#0F172A', fontWeight: 600, letterSpacing: '0.02em', cursor: 'pointer', }} > Return to dashboard </button> )} </div> </div> ); } if (!credentialsReady) { return ( <div data-lk-theme="default" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '2.5rem', background: 'radial-gradient(circle at top, rgba(15, 23, 42, 0.9), #020617)', }} > <div style={{ width: '100%', maxWidth: 540, padding: '2.4rem', borderRadius: '1.4rem', background: 'rgba(15, 23, 42, 0.85)', border: '1px solid rgba(148, 163, 184, 0.28)', boxShadow: '0 30px 80px rgba(15, 23, 42, 0.55)', color: '#E2E8F0', backdropFilter: 'blur(16px)', }} > <p style={{ margin: 0, fontSize: '0.82rem', letterSpacing: '0.08em', textTransform: 'uppercase', color: '#38BDF8' }}>Live Avatar Control</p> <h1 style={{ marginTop: '0.85rem', marginBottom: '0.4rem', fontSize: '2.1rem', fontWeight: 600, color: '#F8FAFC' }}> Prepare your interview room </h1> <p style={{ marginBottom: '1.7rem', color: '#CBD5F5', lineHeight: 1.55 }}>{preJoinStatus}</p> <div style={{ display: 'flex', gap: '0.85rem', flexWrap: 'wrap' }}> <button type="button" onClick={onSetupRoom} disabled={isSettingUp} style={{ flex: '1 1 160px', padding: '0.95rem 1.2rem', borderRadius: '1rem', border: 'none', background: isSettingUp ? 'rgba(56, 189, 248, 0.25)' : 'linear-gradient(135deg, #38BDF8, #6366F1)', color: '#0F172A', fontWeight: 600, letterSpacing: '0.02em', cursor: isSettingUp ? 'wait' : onSetupRoom ? 'pointer' : 'not-allowed', boxShadow: '0 18px 48px rgba(79, 70, 229, 0.35)', transition: 'transform 0.2s ease, box-shadow 0.2s ease', }} > {isSettingUp ? 'Setting up…' : 'Setup room'} </button> <button type="button" disabled style={{ flex: '1 1 160px', padding: '0.95rem 1.2rem', borderRadius: '1rem', border: '1px dashed rgba(148, 163, 184, 0.45)', background: 'rgba(15, 23, 42, 0.55)', color: '#94A3B8', fontWeight: 600, letterSpacing: '0.02em', cursor: 'not-allowed', }} > Waiting for credentials… </button> </div> {errorMessage && ( <div role="alert" style={{ marginTop: '1.7rem', padding: '0.9rem 1rem', borderRadius: '0.9rem', background: 'rgba(248, 113, 113, 0.18)', border: '1px solid rgba(248, 113, 113, 0.35)', color: '#FECACA', fontSize: '0.95rem', lineHeight: 1.5, }} > {errorMessage} </div> )} </div> </div> ); } return ( <LiveKitRoom data-lk-theme="default" token={token ?? undefined} serverUrl={serverUrl ?? undefined} connect audio video options={resolvedRoomOptions} onDisconnected={finalizeEnd} style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', backgroundColor: '#020617' }}> <ActiveRoomLayout hostLabel={hostLabel} roomName={roomName} statusMessage={statusMessage} errorMessage={errorMessage} onFinalizeEnd={finalizeEnd} /> {children} </LiveKitRoom> ); } so her as u can see im hearing my own audio as echo or ghost noises like that instead of participant audio
t
Thanks — I reviewed your component code and the symptom (hearing your own mic as echo/ghost). That almost always means the page is playing your local microphone track back to you while the mic is also being published. Here's exactly what to check and quick fixes you can apply. What to do (apply in this order) 1. Stop rendering your own audio track ◦ Make sure your UI only renders remote participants’ audio. Don’t attach the local participant’s audio track to any <audio> element or component. ◦ Example: filter out the local participant when rendering tracks:
Copy code
const { participants, room } = useRoomContext();
     const remote = Array.from(participants).filter(p => p !== room.localParticipant);

     <TrackLoop participants={remote}>
       <AudioTrack />
     </TrackLoop>
1. Verify you’re not double-publishing or playing forwarded audio ◦ If you forward mic PCM to the LiveAvatar WebSocket, do not also create an audio element that plays that WS stream back into the page. ◦ If you capture getUserMedia separately for forwarding, avoid publishing that second track to LiveKit or playing it locally. 1. Ensure echo cancellation/noise suppression are enabled ◦ In your room options ensure audio capture uses echoCancellation and noiseSuppression:
Copy code
const roomOptions = {
       audioCaptureDefaults: {
         echoCancellation: true,
         noiseSuppression: true,
         autoGainControl: true,
       }
     };
1. If you used ScriptProcessor/AudioContext to forward mic to LiveAvatar, avoid connecting the processor to an output that will play sound ◦ When you create a MediaStreamAudioSourceNode and a ScriptProcessorNode, don’t connect to
audioContext.destination
if that causes playback. (My earlier example connected to destination to avoid silence during development — remove that in production.) 1. Disable preconnect buffering if you see a short ghost at start ◦ If you enabled any preconnect buffer or instant connect, disable it:
Copy code
await room.localParticipant.setMicrophoneEnabled(true, undefined, { preConnectBuffer: false });
1. Confirm you’re using the local microphone track for forwarding ◦ Reuse the LocalParticipant’s microphone MediaStreamTrack for sending PCM to LiveAvatar so there’s a single source of truth (prevents device duplicates and extra permission prompts). If you want I can: • Inspect the exact part of your app that renders audio (VideoConference / TrackLoop usage) and point out where to change it. • Provide a small diff showing how to filter the local participant out of your current layout. • Update your forwarding code so it does not attach to destination (if that’s the current cause). Which would you like me to do next? (Share the snippet that renders participant audio or confirm if you’re using any AudioContext destination connections.) Sources: Noise & echo cancellation | LiveKit docs | Bringing AI avatars to voice agents | Agent speech and audio | LiveKit docs
i
import type { Room } from 'livekit-client'; import * as React from 'react'; /** @public */ export const RoomContext = React.createContext<Room | undefined>(undefined); /** * Ensures that a room is provided via context. * If no room is provided, an error is thrown. * @public */ export function useRoomContext() { const ctx = React.useContext(RoomContext); if (!ctx) { throw Error('tried to access room context outside of livekit room component'); } return ctx; } /** * Returns the room context if it exists, otherwise undefined. * @public */ export function useMaybeRoomContext() { return React.useContext(RoomContext); } /** * Ensures that a room is provided, either via context or explicitly as a parameter. * If no room is provided, an error is thrown. * @public */ export function useEnsureRoom(room?: Room) { const context = useMaybeRoomContext(); const r = room ?? context; if (!r) { throw new Error( 'No room provided, make sure you are inside a Room context or pass the room explicitly', ); } return r; }
t
Thanks — I see you’re using the Room context helpers. The echo means your app is playing back the local mic track. Here’s exactly what to change and a small code snippet you can drop into your layout to prevent hearing yourself. What to do (short) • Don’t render or attach the local participant’s audio track to any audio element. • Render only remote participants’ audio. • If you forward mic audio via WebAudio to LiveAvatar, do NOT connect the processor to
audioContext.destination
. • Ensure echoCancellation/noiseSuppression remain enabled in room options. Snippet — render only remote audio (using Room context)
Copy code
import { useRoomContext } from './RoomContext';
import { TrackLoop, AudioRenderer } from '@livekit/components-react';

function RemoteAudioOnly() {
  const room = useRoomContext();
  const remoteParticipants = Array.from(room.participants.values())
    .filter(p => p.sid !== room.localParticipant?.sid);

  return (
    <TrackLoop participants={remoteParticipants}>
      <AudioRenderer />
    </TrackLoop>
  );
}
If you use other rendering (map over participants), filter out
room.localParticipant
the same way. Forwarding to LiveAvatar — avoid playback • When you set up ScriptProcessor/MediaStreamTrackProcessor to send PCM, remove or comment out any
processor.connect(audioContext.destination)
or any code that attaches the forwarded stream to an <audio> element. • Send mute/unmute events from the local track rather than replaying audio. If you want, paste the component that renders participants (VideoConference / TrackLoop usage) and I’ll show the exact lines to change.
i
i have only one participant
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!