hi, noise cancellation looks like has livekit clou...
# ask-ai
c
hi, noise cancellation looks like has livekit cloud auth. how to use my own noise cancellation
t
Thanks for reaching out, Eray. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're right that LiveKit's enhanced noise cancellation (Krisp) in LiveKit Cloud requires auth. If you want to use your own noise cancellation, you can — process audio before it reaches LiveKit's STT/agents. What I can help with next: • Do you want an example for WebRTC (browser/mobile), an agent written in Python/Node, or SIP/trunking? • Are you processing audio client-side (before send) or server-side (in an agent/process that receives raw frames)? High-level options you can use now: • Agent-level preprocessing: Override the
stt_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 docs
c
The agent interrupts even at the slightest sound. It would be better to apply a filter as soon as the sound occurs. My application is written in Python.
t
Thanks — I’ll help you implement a Python-side filter that activates immediately when sound is detected so small noises won’t cause the agent to interrupt. Quick plan: 1. Detect voice activity with a simple energy/VAD threshold so processing only runs when sound is present. 2. Run your noise-reduction function on incoming `AudioFrame`s while voice is active. 3. Suppress very short noises by requiring a minimum active duration or smoothing the VAD decisions. Example Python pattern to put inside your agent’s
stt_node
(adapt sample rates/format to your app):
Copy code
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?
c
no i dont have a removal func
t
Thanks — since you don't have a noise-removal function yet, here are two practical paths (quick to implement vs higher quality) and a ready Python example you can drop into your
stt_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):
Copy 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?
c
102601.064 ERROR livekit.agents Error in _forward_input Traceback (most recent call last): File "/Users/a/Desktop/b/c/d/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/d/Desktop/a/b/v/.venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 386, in _forward_input async for frame in audio: File "/Users/a/Desktop/b/c/d/e.py", line 126, in filtered_audio is_speech = vad.is_speech(data, SAMPLE_RATE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/d/Desktop/c/a/b/.venv/lib/python3.11/site-packages/webrtcvad.py", line 37, in is_speech return _webrtcvad.process(self._vad, sample_rate, buf, length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
t
You're hitting a WebRTC VAD error when calling
vad.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.