How to properly turn on noiseSuppression and echoC...
# ask-ai
r
How to properly turn on noiseSuppression and echoCancellation on Javascript SDK?
t
Thanks for reaching out, Shreyansh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! To help you enable
noiseSuppression
and
echoCancellation
in the LiveKit JavaScript SDK, you can use the
AudioCaptureOptions
interface when creating or publishing audio tracks. These options tap into the standard WebRTC-based audio processing settings that LiveKit supports, making your audio experience clearer and more enjoyable. Here’s a simple way to enable them:
Copy code
import { createLocalAudioTrack } from 'livekit-client';

// Option 1: Create audio track with noise suppression and echo cancellation
const audioTrack = await createLocalAudioTrack({
  noiseSuppression: true,
  echoCancellation: true,
});

// Option 2: Include in connect options
await room.connect('wss://your-livekit-url', token, {
  audio: {
    noiseSuppression: true,
    echoCancellation: true,
  },
  video: true,
});
These settings directly correspond to the WebRTC
MediaTrackConstraints
for
noiseSuppression
and
echoCancellation
, which browsers use to apply real-time audio processing. It’s a neat way to improve your call quality effortlessly! Just a few helpful notes: • Good news! Both
noiseSuppression
and
echoCancellation
are usually enabled by default in most LiveKit SDKs. • Keep in mind, these features depend on your browser’s WebRTC support. Most modern browsers handle them well, but results can vary a bit. • If you’re looking for even stronger noise cancellation, like filtering out background voices, LiveKit Cloud offers an advanced model powered by Krisp. This requires some extra setup and works only on certain platforms (for example, it’s not available on Safari versions below 17.4). If you want to dive deeper or need more details, feel free to check out the Noise & echo cancellation documentation. We’re here to help you get the best audio experience possible! Sources: src/room/track/options.ts | Noise & echo cancellation | LiveKit Docs
r
Does something like this is not a right setup for noise cancellation and echo cancellation?
Copy code
export const OPTIMAL_AUDIO_CONSTRAINTS: AudioCaptureOptions = {
  // Enable WebRTC's built-in audio processing
  echoCancellation: true,
  noiseSuppression: true,
  autoGainControl: true,

  // Audio quality optimized for voice
  sampleRate: 48000, // High quality sample rate
  channelCount: 1, // Mono for voice calls (saves bandwidth)
  sampleSize: 16, // 16-bit audio

  // Latency optimization
  latency: 0.01, // 10ms target latency
}

useRoom({
  roomOptions: {
    adaptiveStream: {
      pixelDensity: 'screen',
    },
    dynacast: true,

    // Enhanced audio capture defaults
    audioCaptureDefaults: OPTIMAL_AUDIO_CONSTRAINTS,

    videoCaptureDefaults: {
      resolution: {
        width: 1280,
        height: 720,
        frameRate: 30,
      },
    },
    publishDefaults: {
      simulcast: true,
      dtx: true,
      red: true,
      videoEncoding: {
        maxBitrate: 800_000, // Lower bitrate for room scenarios
        maxFramerate: 24,
      },
      screenShareEncoding: {
        maxBitrate: 2_000_000,
        maxFramerate: 15,
      },
      // Enhanced audio settings for better voice quality
      audioPreset: {
        maxBitrate: 96_000, // Higher bitrate for better quality
        priority: 'high', // Prioritize audio over video
      },
    },
  },
})

export function useRoom(options: UseRoomOptions = {}): UseRoomReturn {
  // Create or use existing room instance
  const roomInstance = options.room || new Room(options.roomOptions)

  // Provide the room context - this is the single source of truth
  const room = useProvideRoomContext(roomInstance)

  // Cleanup on unmount
  onBeforeUnmount(async () => {
    if (room.value && room.value.state !== 'disconnected') {
      console.log('[useRoom] Disconnecting room on unmount')
      try {
        await room.value.disconnect()
      } catch (err) {
        console.error('[useRoom] Error disconnecting on unmount:', err)
      }
    }
  })

  return {
    room,
  }
}
t
I'm glad to see that your setup for
noiseSuppression
and
echoCancellation
using
AudioCaptureOptions
is on the right track and fully supported in the LiveKit JavaScript SDK. The properties
echoCancellation
,
noiseSuppression
, and
autoGainControl
work hand-in-hand with WebRTC's MediaStreamTrack constraints to help manage audio processing when creating tracks. Here are a few helpful points about your configuration: •
echoCancellation
,
noiseSuppression
, and
autoGainControl
are all valid and widely used to enhance audio quality. • You can also explore additional constraints like
sampleRate
,
channelCount
, and
latency
to fine-tune the audio experience for your specific needs. • LiveKit takes advantage of WebRTC’s built-in audio processing features, which helps keep things compatible across modern browsers. Using
audioCaptureDefaults
in
useRoom
is a smart approach to set consistent and improved audio capture defaults throughout your app. If anything feels unclear or you’d like some extra help with your setup, please don’t hesitate to reach out. I’m here to support you! Sources: src/room/track/options.ts | Noise & echo cancellation | LiveKit Docs | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...
r
Issue is the noise/echo cancellation does not performs well here, I can still hear some noise in the background
t
Thanks so much for reaching out! To better understand the noise and echo cancellation issues you're experiencing, could you please share a bit more about your setup? For example: • Which browser and version are you using? • Are you testing in a particular environment, like a noisy room or with multiple participants? • Do you happen to use any external audio devices, such as microphones or speakers? Knowing these details will really help us pinpoint what might be affecting the noise and echo cancellation, so we can find the best solution for you.
r
• I am not latest chrome browser • For some participants the noise are coming, like fan sound. But when using google meet, the noise is not coming for that participant • It does not matter what audio device that participant uses, the noise is still there
t
I'm really sorry to hear you're having trouble with noise and echo cancellation. This can definitely be frustrating! The issue you're experiencing is likely because the default WebRTC-based
noiseSuppression
in LiveKit is designed to handle short, occasional noises, but it can struggle a bit with constant background sounds like fan noise. Google Meet uses some pretty sophisticated, machine learning-based noise suppression models that are specially trained to tackle these kinds of persistent noises, which is why it tends to perform better in those situations. To help you get closer to that level of performance in LiveKit, here are a couple of options you might find useful: • Enhanced Noise Cancellation: LiveKit Cloud offers advanced noise cancellation powered by Krisp, which works really well against ongoing noises like fans. It does require some setup and is available on supported platforms. • Krisp Integration: If you're looking for local noise suppression, you can integrate Krisp’s noise filter using the
@livekit/krisp-noise-filter
package. This gives you high-quality noise reduction, though it might use a bit more CPU on devices with lower power. If you’re running a self-hosted deployment, just a heads-up that enhanced noise cancellation isn’t turned on by default and would need to be set up manually. Please don’t hesitate to reach out if you’d like me to walk you through the setup or if you have any other questions—I’m here to help! Sources: Noise & echo cancellation | LiveKit Docs | Enhanced noise cancellation | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs | Sources/LiveKitKrispNoiseFilter/LiveKitKrispNoiseFilter.swift | Optimizing Video Calls for Low-Powered Devices in LiveKit (JS SDK ≥ v2.14.0...
r
I am on cloud also I am using krisp as well here
Copy code
const { connectionState } = useRoomConnection()

export function useRoomConnection(): UseRoomConnectionReturn {
  const roomContext = useRoomContext()

    // Enhanced noise cancellation handler with duplicate prevention
    const handleLocalTrackPublished = async (
      trackPublication: LocalTrackPublication
    ) => {
      if (
        trackPublication.source === Track.Source.Microphone &&
        trackPublication.track instanceof LocalAudioTrack
      ) {
        const trackId =
          trackPublication.trackSid ||
          trackPublication.track.mediaStreamTrack.id

        // Prevent duplicate processing of the same track
        if (processedTracks.has(trackId)) {
          console.log(
            `[useRoomConnection] Audio processing already applied to track ${trackId}, skipping`
          )
          return
        }

        processedTracks.add(trackId)
        console.log(
          `[useRoomConnection] 🎤 Setting up enhanced audio processing for microphone track ${trackId} (room: ${roomName}, total processed: ${processedTracks.size})`
        )

        try {
          // First, ensure WebRTC built-in processing is working
          await applyWebRTCAudioProcessing(trackPublication.track)

          // Then, try to apply Krisp for additional enhancement
          await applyKrispNoiseFilter(trackPublication.track)

          console.log(
            `[useRoomConnection] Enhanced audio processing completed for track ${trackId}`
          )
        } catch (err) {
          console.error(
            `[useRoomConnection] Audio processing setup failed for track ${trackId}:`,
            err
          )
          // Remove from processed set on failure so we can retry
          processedTracks.delete(trackId)
        }
      }
    }

    // Clean up processed tracks when they're unpublished
    const handleLocalTrackUnpublished = (
      trackPublication: LocalTrackPublication
    ) => {
      if (trackPublication.source === Track.Source.Microphone) {
        const trackId =
          trackPublication.trackSid ||
          trackPublication.track?.mediaStreamTrack.id
        if (trackId && processedTracks.has(trackId)) {
          console.log(
            `[useRoomConnection] Cleaning up processed track ${trackId}`
          )
          processedTracks.delete(trackId)
        }
      }
    }

    const handleConnectionStateChanged = (state: LiveKitConnectionState) => {
      console.log('[useRoomConnection] Connection state changed:', state)
      connectionState.value = state
    }
}

async function applyKrispNoiseFilter(track: LocalAudioTrack): Promise<void> {
  try {
    const krispModule = await loadEnhancedKrispFromCDN()

    if (!krispModule) {
      console.warn(
        '[useRoomConnection] Krisp module not available, using WebRTC processing only'
      )
      return
    }

    const { KrispNoiseFilter, isKrispNoiseFilterSupported } = krispModule

    if (!isKrispNoiseFilterSupported()) {
      console.warn(
        '[useRoomConnection] Krisp not supported, WebRTC processing will handle noise reduction'
      )
      return
    }

    // Create Krisp processor with optimized settings for voice calls
    const krispProcessor = KrispNoiseFilter({
      model: 'meeting', // Optimized for meeting scenarios
      aggressiveness: 0.7, // Balanced approach - not too aggressive to avoid cutting off speech
    })

    console.log('[useRoomConnection] Applying enhanced Krisp noise filter')

    // Wrap Krisp processor to be compatible with LiveKit interface
    const processorWrapper = new KrispProcessorWrapper(krispProcessor)

    // Apply the processor to the track
    await track.setProcessor(processorWrapper)
    await processorWrapper.setEnabled(true)

    // Monitor processor performance
    monitorAudioProcessor(krispProcessor, track)

    console.log(
      '[useRoomConnection] Enhanced Krisp filter enabled successfully'
    )
  } catch (err) {
    console.warn(
      '[useRoomConnection] Krisp setup failed, falling back to WebRTC processing:',
      err
    )
    // Fallback is already in place via WebRTC processing
  }
}

async function loadEnhancedKrispFromCDN(): Promise<EnhancedKrispModule | null> {
  // Return cached module if already loaded
  if (krispModuleCache) {
    console.log('[useRoomConnection] Using cached enhanced Krisp module')
    return krispModuleCache as EnhancedKrispModule
  }

  // Return existing load promise if already loading
  if (krispLoadPromise) {
    console.log(
      '[useRoomConnection] Enhanced Krisp already loading, waiting...'
    )
    return krispLoadPromise as Promise<EnhancedKrispModule | null>
  }

  krispLoadPromise = Promise.race([
    // Dynamic import with timeout
    import(
      /* webpackIgnore: true */ /* @vite-ignore */ // @ts-expect-error ignore
      'https://cdn.jsdelivr.net/npm/@livekit/krisp-noise-filter@0.3.4/+esm'
    ).then(module => {
      console.log(
        '[useRoomConnection] Enhanced Krisp loaded from CDN successfully'
      )
      krispModuleCache = module as EnhancedKrispModule
      return krispModuleCache as EnhancedKrispModule
    }),
    // Timeout promise
    new Promise<null>((_, reject) => {
      setTimeout(() => {
        reject(new Error('Enhanced Krisp load timeout'))
      }, KRISP_LOAD_TIMEOUT)
    }),
  ]).catch(error => {
    console.error(
      '[useRoomConnection] Failed to load enhanced Krisp from CDN:',
      error
    )
    krispLoadPromise = null // Reset to allow retry
    return null
  })

  return krispLoadPromise as Promise<EnhancedKrispModule | null>
}
t
It looks like you’re using Krisp noise cancellation in LiveKit Cloud, but the noise suppression isn’t quite working as well as you’d hoped. Let’s explore some possible reasons and ways to improve it together: • Double Processing: Sometimes noise cancellation can be applied twice—once on the frontend and again in the agent code. To keep your audio clear, make sure it’s only applied in one place. • Platform Limitations: The advanced Background Voice Cancellation (BVC) model isn’t available on frontend platforms like Web. If you’re using the standard Krisp model, it might struggle with steady noises like fans compared to BVC. • Browser Compatibility: It’s a good idea to check if your browser supports Krisp. For instance, Safari versions before 17.4 don’t support Krisp noise cancellation yet. • Initialization: Please double-check that Krisp is properly initialized and authorized. If it’s not loaded correctly, it will default to WebRTC’s noise suppression, which isn’t as strong. • Configuration: Make sure the Krisp noise filter is correctly applied to the audio track. Sometimes a small setup hiccup can affect performance. From what I see, you’re dynamically loading the Krisp module and applying it to the audio track. Here are a couple of things to keep an eye on: • Ensure the
applyKrispNoiseFilter
function completes smoothly without falling back on WebRTC processing. • Consider adjusting the
aggressiveness
parameter in the Krisp processor—sometimes increasing it just a bit helps tackle persistent background noises better. If you keep running into issues, please don’t hesitate to reach out. I’m here to help you debug or fine-tune your setup so you get the best audio experience possible! Sources: LICENSE | agent.py | Noise & echo cancellation | LiveKit Docs | Enhanced noise cancellation | LiveKit Docs