Skip to content
Aditya Bhalsod
← Open Source
Open SourceIntermediate

Ducking Windows Volume With WebRTC VAD Without Flapping

How py-music-duck turns 30 ms microphone frames into a steady duck-and-restore decision with an RMS gate, WebRTC VAD, a vote window and a hold timer.

  • #python
  • #windows
  • #audio
  • #webrtc-vad
Contents
  1. Capture on one thread, decide on another
  2. A frame is 30 ms of 16 kHz audio
  3. Two gates and a vote
  4. Quick down, slow up
  5. Remembering the volume
  6. Where it stops working

py-music-duck is one Python script, auto_duck.py. It lowers the Windows master volume while it hears speech on the microphone, then restores it after a short silence. WebRTC VAD (voice activity detection) decides what counts as speech, and Pycaw sets the volume.

Asking "is this frame speech?" is the easy part. The work is in making the answer steady, so the volume does not drop on a single click and does not creep back up between two sentences. This post follows the detection loop and uses the constants from the script.

Capture on one thread, decide on another

PortAudio calls audio_callback with each block of microphone samples. The docstring says the callback should stay fast, so it only copies the bytes onto a queue.Queue. The decision loop, process_audio, reads from that queue.

The queue holds at most 100 frames (max_queue_size). When it is full, the callback drops the oldest frame and adds the new one. That matters because the loop is sometimes busy: a volume fade sleeps inside it for a quarter of a second.

A frame is 30 ms of 16 kHz audio

WebRTC VAD judges one short frame at a time. A comment in Config notes that it supports 10, 20 or 30 ms frames, and SUPPORTED_VAD_SAMPLE_RATES lists 8000, 16000, 32000 and 48000 Hz. The script uses 30 ms at 16,000 Hz, mono, 16-bit.

Python
@dataclass
class Config:
    sample_rate: int = 16_000
    frame_duration_ms: int = 30
    channels: int = 1
    vad_mode: int = 2          # 0 = least aggressive, 3 = most
    min_rms: float = 350.0     # speech must also be louder than this
    speech_window_frames: int = 8
    required_speech_frames: int = 4
    silence_restore_seconds: float = 1.5
    duck_volume_percent: float = 15.0
    fade_duration_seconds: float = 0.25
    fade_steps: int = 10
    max_queue_size: int = 100

The frame size is derived, not typed in: int(sample_rate * frame_duration_ms / 1000). That is 480 samples, or 960 bytes of int16 audio. The same number goes to sd.RawInputStream as blocksize, so each callback delivers exactly one frame. Before listening starts, sd.check_input_settings asks PortAudio whether the microphone can open the chosen rate. If it cannot, the script stops with an error that names the rate.

Two gates and a vote

is_speech runs two checks. The first is cheap: it computes the root mean square (RMS) of the frame and returns False if it is below min_rms. A value of 350 is about 1% of the 16-bit range, which tops out at 32,768. Only louder frames reach the second check, the VAD itself, created with vad_mode 2 on a 0 to 3 aggressiveness scale. If the VAD raises an error, the frame counts as silence.

Python
rms = self.calculate_rms(pcm_data)
if rms < self.config.min_rms:
    return False, rms
try:
    speech = self.vad.is_speech(pcm_data, self.config.sample_rate)
    return speech, rms
except Exception as exc:
    print(f"VAD error: {exc}", file=sys.stderr)
    return False, rms

One frame is still not enough to act on. Each result goes into a deque with maxlen=8, and confirmed_speech is true when at least 4 of those 8 are True. That is 120 ms of speech-like audio inside a 240 ms window. The four do not have to be consecutive, so a hesitant voice still counts and one stray frame never does. The command line exposes --rms and --vad-mode, but not the window size.

Quick down, slow up

Ducking needs the vote. Restoring needs time.

Python
speech, rms = self.is_speech(pcm_data)
self.speech_history.append(speech)

if speech:
    self.last_voice_time = time.monotonic()

if self.confirmed_speech():
    self.last_voice_time = time.monotonic()
    if not self.ducked:
        self.duck_volume()
else:
    self.check_restore()

last_voice_time is refreshed by any speech frame and by any frame where the vote still holds. check_restore runs when the vote fails, and also when the queue stays empty for 0.1 seconds, so the timer keeps counting even if no audio arrives. Restore happens once time.monotonic() - last_voice_time reaches silence_restore_seconds, which is 1.5 seconds.

The asymmetry is deliberate: four speech frames to duck, 1.5 seconds of quiet to come back. A pause between sentences is shorter than that, so the volume stays down through a conversation and recovers only when it really stops.

Remembering the volume

Before duck_volume changes anything, it reads the master volume with GetMasterVolumeLevelScalar (0.0 to 1.0, multiplied by 100) and keeps it in self.original_volume. If the volume is already at or below the 15% target, it only sets ducked, so a later restore returns to the same value. Otherwise fade_to walks there in 10 steps over 0.25 seconds.

Python
value = start_percent + (target_percent - start_percent) * step / steps
self.set_volume(value)
time.sleep(interval)

Restoring fades back to the saved value, then resets state in a finally block:

Python
try:
    self.volume.fade_to(target)
except Exception as exc:
    print(f"Unable to restore volume: {exc}")
finally:
    self.original_volume = None
    self.ducked = False
    self.speech_history.clear()

Clearing the vote history means the next duck starts from a blank window. On exit, SIGINT and SIGTERM handlers call controller.stop(), which restores the volume if it is still ducked.

Where it stops working

The saved volume is read once. If you change the volume while it is ducked, the restore fades back to the old value. If a restore fails, the error is printed and the saved value is dropped, with no retry. The detector only hears the microphone signal: it cannot tell whose voice it is, and the RMS gate and VAD mode are the only filters. The README says microphone gain and room noise strongly affect the best settings, so expect to tune.

The Windows-specific code is the Pycaw volume controller. The rest (a queue, a loudness gate, a vote, a hold timer, save-then-restore) is not tied to Windows.

Found this useful? Share it with your team.

Keep reading

More from Open Source and beyond