colossal-glass-16853
12/12/2025, 7:16 AMtall-airline-16756
12/12/2025, 7:16 AMtall-airline-16756
12/12/2025, 7:16 AMstt_node (or equivalent STT hook) to run each incoming AudioFrame through your noise-removal function, then pass the cleaned frames to the default STT pipeline.
• Input-stream preprocessing: Wrap the input AudioStream with your processor so LiveKit receives already-filtered audio.
• SIP/trunk setup: Disable built-in krisp_enabled on the trunk and apply your NC in the SIP media flow or in your agent that handles the call.
If you tell me your environment (WebRTC agent language or SIP), I’ll provide a concise code snippet tailored to that setup.
Sources: Enhanced noise cancellation | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | SIP APIs | LiveKit docscolossal-glass-16853
12/12/2025, 7:20 AMtall-airline-16756
12/12/2025, 7:20 AMstt_node (adapt sample rates/format to your app):
import collections
import math
from typing import AsyncIterable, Optional
VOICE_ENERGY_THRESHOLD = 300 # tune this
MIN_ACTIVE_FRAMES = 5 # require N frames before treating as active
SILENCE_FRAMES_TO_END = 10 # require N silent frames to end activity
def frame_energy(frame):
# frame.data assumed bytes of 16-bit PCM little-endian
import struct
samples = struct.unpack('<' + 'h' * (len(frame.data)//2), frame.data)
return sum(abs(s) for s in samples) / max(1, len(samples))
async def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings) -> Optional[AsyncIterable[stt.SpeechEvent]]:
active_count = 0
silence_count = 0
buffer = collections.deque() # hold frames while deciding
async def filtered_audio():
nonlocal active_count, silence_count
async for frame in audio:
e = frame_energy(frame)
if e >= VOICE_ENERGY_THRESHOLD:
active_count += 1
silence_count = 0
else:
if active_count > 0:
silence_count += 1
else:
# still in pre-activation buffering
silence_count = 0
buffer.append(frame)
# Start processing only after voice sustained for MIN_ACTIVE_FRAMES
if active_count >= MIN_ACTIVE_FRAMES:
# process buffered frames first
while buffer:
f = buffer.popleft()
processed = your_noise_removal_function(f.data, f.sample_rate)
yield rtc.AudioFrame(data=processed, sample_rate=f.sample_rate, num_channels=f.num_channels, samples_per_channel=f.samples_per_channel)
# from now on process frames in real-time
active_count = MIN_ACTIVE_FRAMES # cap
else:
# if not yet active, keep buffering but drop very old frames to limit memory
while len(buffer) > 50:
buffer.popleft()
# End voice activity after SILENCE_FRAMES_TO_END silent frames
if active_count > 0 and silence_count >= SILENCE_FRAMES_TO_END:
active_count = 0
silence_count = 0
buffer.clear()
return Agent.default.stt_node(self, filtered_audio(), model_settings)
Tuning notes (what to adjust):
• VOICE_ENERGY_THRESHOLD: higher to ignore low-level noise, lower to be more sensitive.
• MIN_ACTIVE_FRAMES: raise to avoid triggering on very short sounds.
• SILENCE_FRAMES_TO_END: raise to avoid chopping speech during brief pauses.
• Frame length: ensure your frames are small enough for responsiveness (e.g., 10–30 ms) but not too small to be noisy.
If you already have a specific your_noise_removal_function(...) (library or model), tell me its input/output format and frame size and I’ll tailor the snippet to match it and suggest concrete threshold values. Would you like that?colossal-glass-16853
12/12/2025, 7:23 AMtall-airline-16756
12/12/2025, 7:23 AMstt_node.
Which to pick
• Quick/local (low complexity): Use a simple spectral noise gate + VAD. Fast, runs locally, reduces short noises and false triggers.
• Higher quality (better suppression): Use an external library or ML model (RNNoise, WebRTC VAD + denoiser, or a pretrained NN). More setup but much better results.
Recommended libraries
• RNNoise (good balance of quality/simplicity). C library with Python bindings (e.g., rnnoise‑py).
• WebRTC VAD for robust voice activity detection (webrtcvad Python package).
• Noisereduce (Python) for a simple spectral subtraction approach.
Minimal working approach (spectral gate + VAD) 1) Use webrtcvad to detect voice activity reliably. 2) When VAD says voice, run a per-frame spectral gate (or noisereduce) on a short buffer of frames. 3) Feed cleaned frames to the STT pipeline.
Example: VAD + simple spectral reduction using noisereduce
• Install: pip install webrtcvad noisereduce numpy soundfile
Drop this pattern into your stt_node (adapt names/types to your code):
import asyncio
import collections
import numpy as np
import webrtcvad
import noisereduce as nr
import struct
VAD_AGGRESSIVENESS = 2 # 0-3
FRAME_MS = 20 # frame size in ms
SAMPLE_RATE = 16000
BYTES_PER_SAMPLE = 2
vad = webrtcvad.Vad(VAD_AGGRESSIVENESS)
def bytes_to_float32(data):
ints = np.frombuffer(data, dtype=np.int16)
return ints.astype(np.float32) / 32768.0
def float32_to_bytes(floats):
ints = (floats * 32767).astype(np.int16)
return ints.tobytes()
async def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings):
buffer = collections.deque()
active = False
prebuffer_frames = int(200 / FRAME_MS) # keep 200ms pre-roll
async def filtered_audio():
nonlocal active
async for frame in audio:
# assume frame.data is 16-bit PCM little-endian
data = frame.data
buffer.append(frame)
if len(buffer) > prebuffer_frames:
buffer.popleft()
# VAD expects raw bytes of frame length in ms
is_speech = vad.is_speech(data, SAMPLE_RATE)
if is_speech:
active = True
# gather buffered frames into numpy audio for processing
frames = b"".join(f.data for f in buffer)
audio_float = bytes_to_float32(frames)
# run noise reduction on the buffered audio
reduced = nr.reduce_noise(y=audio_float, sr=SAMPLE_RATE, prop_decrease=1.0)
# split back into frame-sized chunks and yield
frame_bytes = [reduced[i:i + (FRAME_MS * SAMPLE_RATE // 1000)] for i in range(0, len(reduced), (FRAME_MS * SAMPLE_RATE // 1000))]
for chunk in frame_bytes:
yield rtc.AudioFrame(
data=float32_to_bytes(chunk),
sample_rate=frame.sample_rate,
num_channels=frame.num_channels,
samples_per_channel=frame.samples_per_channel,
)
buffer.clear()
else:
# if not active, optionally pass through or mute to avoid false triggers
if active:
# allow short silence before ending activity
# yield muted frames or normal frames as needed
yield frame
else:
# drop or yield muted frames to avoid STT trigger
pass
return Agent.default.stt_node(self, filtered_audio(), model_settings)
Tuning tips
• Use WebRTC VAD aggressiveness 2–3 to reduce false positives.
• Keep FRAME_MS at 10–30 ms for responsiveness.
• For noisereduce, adjust prop_decrease and window sizes to balance quality vs latency.
• If latency matters, process small buffered windows (100–300 ms) only when VAD triggers, then stream cleaned frames.
If you want, I can:
• Provide an RNNoise example (better results, requires building native bindings), or
• Tailor thresholds/frame sizes to your exact frame format (send one sample AudioFrame structure — sample rate, bytes per frame). Which would you prefer?colossal-glass-16853
12/12/2025, 7:27 AMtall-airline-16756
12/12/2025, 7:27 AMvad.is_speech(data, SAMPLE_RATE). That method requires the audio buffer to match specific conditions. To help debug and give a corrected snippet, please confirm these four frame details from your `AudioFrame`:
1. Sample rate (e.g., 8000, 16000)
2. Frame duration in ms (frame length) or bytes per frame
3. Encoding/format (e.g., 16-bit PCM little-endian signed int)
4. Number of channels (1 = mono, 2 = stereo)
Quick checklist/fixes you can try immediately:
• Ensure frames are mono 16-bit PCM. WebRTC VAD only accepts 8/16k/32k/48k sample rates and mono PCM.
• Ensure the frame length is exactly 10, 20, or 30 ms. VAD rejects other lengths.
• Pass raw bytes of that exact frame (not a concatenation of multiple frames) to is_speech.
• If your frames are stereo, convert to mono first (e.g., average channels).
If you share the four details above (or paste a single AudioFrame summary), I’ll give a corrected filtered_audio snippet that matches your frame format.