icy-beard-64788
12/10/2025, 6:29 AMtall-airline-16756
12/10/2025, 6:29 AMtall-airline-16756
12/10/2025, 6:29 AMicy-beard-64788
12/10/2025, 6:29 AMtall-airline-16756
12/10/2025, 6:30 AMAudioStream (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 docsicy-beard-64788
12/10/2025, 7:52 AMtall-airline-16756
12/10/2025, 7:53 AMAudioTrack 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.icy-beard-64788
12/10/2025, 7:53 AMtall-airline-16756
12/10/2025, 7:54 AM// 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.icy-beard-64788
12/10/2025, 7:56 AMtall-airline-16756
12/10/2025, 7:56 AMimport 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.icy-beard-64788
12/10/2025, 7:58 AMtall-airline-16756
12/10/2025, 7:58 AMicy-beard-64788
12/10/2025, 7:59 AMtall-airline-16756
12/10/2025, 7:59 AMicy-beard-64788
12/10/2025, 8:01 AMtall-airline-16756
12/10/2025, 8:01 AMimport { 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 docsicy-beard-64788
12/10/2025, 11:01 AMtall-airline-16756
12/10/2025, 11:01 AMconst { 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:
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:
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 docsicy-beard-64788
12/10/2025, 11:03 AMtall-airline-16756
12/10/2025, 11:03 AMaudioContext.destination.
• Ensure echoCancellation/noiseSuppression remain enabled in room options.
Snippet — render only remote audio (using Room context)
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.icy-beard-64788
12/10/2025, 11:13 AMtall-airline-16756
12/10/2025, 11:13 AM