11. Short-time energy, zero crossings and voice activity detection

Recognisers, codecs and diarisers first make an inexpensive decision: whether a frame contains speech. Voice activity detection (VAD) makes that decision from two per-frame features that date back to the 1970s: short-time energy (speech is louder than the background) and the zero-crossing rate (voiced sounds cross zero slowly, fricatives and noise quickly). This notebook computes both with NumPy on a synthetic utterance and reproduces the library’s VAD decisions exactly.

Learning outcomes. After this notebook you can

  • frame a signal and compute short-time RMS level (dBFS) and zero-crossing rate (ZCR);

  • predict both features for silence, voiced and unvoiced frames;

  • configure VadConfig and explain the regions returned by speech_regions;

  • convert between the library’s two ZCR conventions (per frame, per sample) and crossings per second.

import numpy as np
import matplotlib.pyplot as plt
import librosa
import audio_samples as aus

rng = np.random.default_rng(0)
F64 = np.dtype("float64")  # the generators take a numpy dtype instance

Concept

Framing. The signal \(x[n]\) (samples scaled to \([-1, 1]\)) is cut into frames of \(F\) samples that start every \(H\) samples; frame \(m\) covers \(n = mH, \dots, mH + F - 1\). Typical speech settings are \(F = 25\) ms and \(H = 10\) ms, i.e. \(F = 400\) and \(H = 160\) at \(f_s = 16\) kHz (the sample rate in Hz).

Short-time energy is reported as an RMS level in dBFS:

\[r_m = \sqrt{\frac{1}{F} \sum_{i=0}^{F-1} x^2[mH + i]}, \qquad L_m = 20 \log_{10} r_m\ \text{dBFS}\]

where \(r_m\) is the frame RMS (dimensionless, full scale = 1) and \(L_m\) the level in decibels relative to full scale. 0 dBFS is an RMS of 1, so a full-scale sine is at \(-3.01\) dBFS in this convention. dBFS says nothing about loudness in the room: the same file can be played at any volume (notebook 14).

Zero-crossing rate (ZCR) counts sign changes:

\[z_m = \frac{\#\{\text{sign changes in frame } m\}}{F - 1}\]

in crossings per sample. A sinusoid at \(f\) Hz crosses zero \(2f\) times per second, so \(z \approx 2f / f_s\); conversely a ZCR of \(z\) corresponds to a “dominant frequency” of about \(z f_s / 2\) Hz. White noise changes sign on about half of all sample pairs, \(z \approx 0.5\).

Three classes of speech frame:

class

energy

ZCR

silence (background)

low

high (noise-like)

voiced (vowels, nasals)

high

low (periodic, energy below 1 kHz)

unvoiced (fricatives such as /s/)

medium

high (noise-like, energy at 4-8 kHz)

Decision rules. An energy VAD marks frame \(m\) as speech if \(L_m \ge T\), where \(T\) is a threshold in dBFS, equivalently \(r_m \ge 10^{T/20}\). A combined VAD also requires \(z_{min} \le z_m \le z_{max}\), which rejects low hum and noise-like frames (and, as shown below, fricatives).

Post-processing. Raw decisions change state from frame to frame. The library smooths them with a causal majority vote over \(S\) frames, then applies hangover: after the last active frame the next \(H_o\) frames stay active, which bridges short pauses at the cost of a later offset. Finally, speech runs shorter than a minimum and silence gaps shorter than a minimum are removed.

Two ZCR conventions in the library. The VAD’s ZCR is per frame, in crossings per sample, and skips exact zeros. AudioSamples.zero_crossing_rate() is for the whole signal and is in crossings per second; its crossing rule treats an exact zero as non-positive. The frame-wise zero_crossing_rate_frames() uses centred frames and divides by the frame length, so we compute the VAD’s version ourselves.

With the library

Build an utterance at 16 kHz with the generators: 300 ms of silence, a 400 ms “vowel” (harmonics of 200 Hz shaped by a resonance at 700 Hz), a 200 ms “fricative” (white noise of amplitude 0.1), 300 ms of silence, plus a \(-64.8\) dBFS noise floor (uniform noise of amplitude \(10^{-3}\)).

sr = 16_000
partials = [(200.0 * k, 0.3 / (1 + ((200.0 * k - 700) / 200) ** 2)) for k in range(1, 21)]
vowel = aus.compound_tone(partials, 0.4, sample_rate=sr, dtype=F64).to_numpy()
fricative = aus.white_noise(0.2, sample_rate=sr, amplitude=0.1, dtype=F64, seed=1).to_numpy()
floor = aus.white_noise(1.2, sample_rate=sr, amplitude=1e-3, dtype=F64, seed=2).to_numpy()
x = np.concatenate([np.zeros(4_800), vowel, fricative, np.zeros(4_800)]) + floor
audio = aus.AudioSamples.new_mono(x, sr)
assert len(x) == 19_200

VadConfig is immutable and its constructor takes every field. A small helper copies the defaults and overrides a few. We run an energy VAD with 25 ms frames, 10 ms hop, a \(-40\) dBFS threshold and no smoothing or minimum-run rules, so that only the threshold and a 1-frame hangover act.

FIELDS = ["frame_size", "hop_size", "pad_end", "energy_threshold_db", "zcr_min", "zcr_max",
          "min_speech_frames", "min_silence_frames", "hangover_frames", "smooth_frames",
          "speech_band_low_hz", "speech_band_high_hz", "spectral_ratio_threshold"]


def vad_config(method=aus.VadMethod.energy, **overrides):
    base = aus.VadConfig.default()
    kwargs = {name: getattr(base, name) for name in FIELDS}
    kwargs.update(overrides)
    return aus.VadConfig(method, base.channel_policy, **kwargs)


cfg = vad_config(aus.VadMethod.energy, frame_size=400, hop_size=160, energy_threshold_db=-40.0,
                 smooth_frames=1, min_speech_frames=0, min_silence_frames=0, hangover_frames=1)
mask = np.array(audio.voice_activity_mask(cfg))
assert len(mask) == 120  # ceil(19200 / 160) frames (pad_end = True)

# Vowel + fricative form one region, samples 4480..14960 = 0.280-0.935 s
# (the true speech is 0.300-0.900 s).
regions = audio.speech_regions(cfg)
print(regions)
assert regions == [(4_480, 14_960)]

# The combined rule (energy AND 0.02 <= ZCR <= 0.30) rejects the noise-like fricative and
# keeps only the vowel (true extent 4800..11200).
combined = vad_config(aus.VadMethod.combined, frame_size=400, hop_size=160,
                      energy_threshold_db=-40.0, smooth_frames=1, min_speech_frames=0,
                      min_silence_frames=0, hangover_frames=1)
assert audio.speech_regions(combined) == [(4_640, 11_600)]
[(4480, 14960)]

The boundaries follow from the framing. The region starts at the first frame that overlaps the vowel at all: frame 28 starts at sample \(28 \cdot 160 = 4480\) and its last 80 samples are vowel, which is enough to exceed \(-40\) dBFS. It ends at the end of the first inactive frame after the hangover: the last frame touching the fricative is frame 89, hangover keeps frame 90 active, and frame 91 ends at \(91 \cdot 160 + 400 = 14\,960\). The combined region starts one frame later because frame 28 is mostly noise floor and so has a noise-like ZCR.

active = np.flatnonzero(mask)
assert active[0] == 28 and active[-1] == 90
assert 28 * 160 == 4_480 and 28 * 160 + 400 - 4_800 == 80  # 80 vowel samples in frame 28
assert (89 * 160 < 14_400 <= 90 * 160)  # frame 89 is the last that touches the fricative
assert 91 * 160 + 400 == 14_960

How it works

Compute the two features for every frame with NumPy, check them against theory, and rebuild the VAD mask with nothing but a threshold and a hangover counter.

F, H = 400, 160
n_frames = -(-len(x) // H)  # ceil
padded = np.concatenate([x, np.zeros(F)])  # a short last frame counts as zero-padded
frames = np.stack([padded[m * H:m * H + F] for m in range(n_frames)])

rms = np.sqrt(np.mean(frames**2, axis=1))  # divide by the full frame length F


def zcr_frame(fr):
    s = np.sign(fr[fr != 0])  # skip exact zeros
    return np.count_nonzero(s[1:] != s[:-1]) / (F - 1)


zcr = np.array([zcr_frame(fr) for fr in frames])
L = 20 * np.log10(rms)

sil, vow, fri = 10, 50, 78  # frames at 0.1, 0.5 and 0.78 s
# Silence: the noise floor, RMS 1e-3/sqrt(3) = -64.8 dBFS (random: +-1 dB).
assert abs(20 * np.log10(1e-3 / np.sqrt(3)) + 64.8) < 0.05
assert abs(L[sil] + 64.8) < 1.0
# Vowel: RMS sqrt(sum a_k^2 / 2) = -11.7 dBFS. A 25 ms frame holds exactly 5 periods of
# 200 Hz, so the frame RMS matches to 0.05 dB.
vowel_rms = np.sqrt(sum(a**2 / 2 for _, a in partials))
assert abs(20 * np.log10(vowel_rms) + 11.7) < 0.05
assert abs(L[vow] - 20 * np.log10(vowel_rms)) < 0.05
# Fricative: uniform noise of amplitude 0.1, RMS 0.1/sqrt(3) = -24.8 dBFS (+-0.5 dB).
assert abs(L[fri] + 24.8) < 0.5
# ZCR: noise-like frames near 0.5; the vowel near 2 * 780 / 16000 = 0.098, set by its
# strongest partials (600 and 800 Hz).
assert abs(zcr[sil] - 0.5) < 0.06 and abs(zcr[fri] - 0.5) < 0.06
assert 0.06 < zcr[vow] < 0.11
print(f"silence  : {L[sil]:6.1f} dBFS, ZCR {zcr[sil]:.3f}")
print(f"vowel    : {L[vow]:6.1f} dBFS, ZCR {zcr[vow]:.3f}")
print(f"fricative: {L[fri]:6.1f} dBFS, ZCR {zcr[fri]:.3f}")
silence  :  -64.4 dBFS, ZCR 0.484
vowel    :  -11.7 dBFS, ZCR 0.098
fricative:  -25.2 dBFS, ZCR 0.516

Independent reference. librosa.feature.rms with center=False computes the same frame RMS for every full frame. librosa’s zero_crossing_rate divides by \(F\) instead of \(F - 1\) and also counts a crossing between a frame’s first sample and the sample before it, so after rescaling by \(F/(F-1)\) the two can differ by one crossing, \(1/(F-1)\).

full = (len(x) - F) // H + 1  # frames that fit entirely inside the signal
rms_lr = librosa.feature.rms(y=x, frame_length=F, hop_length=H, center=False)[0]
assert len(rms_lr) == full
# librosa returns float32 here, so agreement is to float32 precision (1e-6 relative).
assert np.allclose(rms[:full], rms_lr, rtol=1e-6, atol=0)
zcr_lr = librosa.feature.zero_crossing_rate(x, frame_length=F, hop_length=H, center=False)[0]
assert np.all(np.abs(zcr[:full] - zcr_lr * F / (F - 1)) <= 1 / (F - 1) + 1e-6)
def hangover(raw, n_hold):
    # After the last active frame, keep the next n_hold frames active.
    out, hold = [], 0
    for v in raw:
        if v:
            hold = n_hold
            out.append(True)
        elif hold > 0:
            hold -= 1
            out.append(True)
        else:
            out.append(False)
    return np.array(out)


# The energy VAD: threshold, then a hangover of one frame.
thr = 10 ** (-40 / 20)
mine = hangover(rms >= thr, 1)
assert np.array_equal(mine, mask)  # identical decisions

# Combined rule: energy AND zcr_min <= z <= zcr_max, then the same hangover.
mine_c = hangover((rms >= thr) & (zcr >= 0.02) & (zcr <= 0.30), 1)
assert np.array_equal(mine_c, audio.voice_activity_mask(combined))
t_frames = (np.arange(n_frames) * H + F / 2) / sr
fig, axes = plt.subplots(3, 1, figsize=(8, 6), sharex=True)
axes[0].plot(np.arange(len(x)) / sr, x, lw=0.5)
for a, b in regions:
    axes[0].axvspan(a / sr, b / sr, color="C1", alpha=0.2, label="energy VAD region")
axes[0].set(ylabel="Amplitude", title="Synthetic utterance: silence, vowel, /s/, silence")
axes[0].legend(fontsize=8, loc="upper right")
axes[1].plot(t_frames, L)
axes[1].axhline(-40, color="grey", ls="--", lw=0.8)
axes[1].set(ylabel="Level (dBFS)")
axes[2].plot(t_frames, zcr)
axes[2].axhspan(0.02, 0.30, color="C2", alpha=0.15)
axes[2].set(ylabel="ZCR (crossings/sample)", xlabel="Time (s)")
fig.tight_layout()
plt.show()
../_images/f6316764cc49db65bd1b148bab2bc27469a64cadff249eb81113b4098fb86bb0.png

The whole-signal ZCR. zero_crossing_rate() is zero_crossings() divided by the duration in seconds. A 500 Hz tone for 1 s gives about \(2 \cdot 500 = 1000\) crossings per second, which is \(1000/16\,000 = 0.0625\) crossings per sample.

tone = aus.sine_wave(500.0, 1.0, sample_rate=16_000, amplitude=0.5, dtype=F64)
per_second = tone.zero_crossing_rate()
assert per_second == tone.zero_crossings() / 1.0
# Within 2 crossings of 1000 (depends on where the first and last samples fall).
assert abs(per_second - 1_000) <= 2
assert abs(per_second / 16_000 - 0.0625) < 2e-4
# The same count by hand, with the library's rule (zero counts as non-positive).
s = tone.to_numpy() > 0
assert np.count_nonzero(s[1:] != s[:-1]) == tone.zero_crossings()

Ask the library to explain

VadConfig.explain(sample_rate, n_samples=...) converts frames, hops and hangover into milliseconds and the ZCR window into equivalent tone frequencies. The default configuration (1024-sample frames) is tuned for music-rate audio; at 16 kHz the explainer reports that its frames are long for speech.

doc = aus.VadConfig.default().explain(16_000.0, n_samples=19_200)
doc

Voice activity detection

Each 1024-sample frame (hop 512) is classified as speech by its RMS level (≥ -40 dBFS), then the decisions are smoothed by a 5-frame majority vote, extended by 2 hangover frame(s), and runs shorter than 3 speech / 5 silence frames are removed.

Formulas

Frame RMS; F’ is the available frame length and N_d = F when pad_end is set (the missing tail counts as zeros), else F’:

$$ r = \sqrt{\frac{1}{N_d} \sum_{i=0}^{F’-1} x^2[mH + i]} $$

Zero-crossing rate in crossings per sample; a sinusoid at f gives z ≈ 2f/f_s:

$$ z = \frac{#{\text{sign changes, zeros skipped}}}{F - 1} $$

Energy decision against the threshold T (dBFS):

$$ r \ge 10^{\frac{T}{20}} $$

Causal majority vote over the last S frames (ties count as speech); then hangover, minimum-speech and minimum-silence run rules:

$$ \tilde{v}[m] = \left[ 2 \sum_{j=m-S+1}^{m} v[j] \ge \min(m+1, S) \right] $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $F$ | frame size | 1024 samples | | $H$ | hop size | 512 samples | | $T$ | energy threshold | -40 dBFS | | $z_{min}, z_{max}$ | ZCR bounds | 0.02, 0.3 crossings/sample | | $S$ | smoothing window | 5 frames |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Threshold RMS | $10^{T/20}$ = 0.01 | $10^{T/20}$ | | Overlap | $1 - H/F$ = 50 % | $100(1 - H/F)$ | | Frame duration | $F / f_s$ = 64 ms | $1000 F / f_s$ | | Hop duration | $H / f_s$ = 32 ms | $1000 H / f_s$ | | Hangover | $H_o H / f_s$ = 64 ms | $\text{hangover} \cdot H / f_s$ | | Shortest speech region kept | $\text{min}s H / f_s$ = 96 ms | $\text{min_speech} \cdot H / f_s$ | | Shortest silence gap kept | $\text{min}g H / f_s$ = 160 ms | $\text{min_silence} \cdot H / f_s$ | | ZCR lower bound as a tone | $z{min} f_s / 2$ = 160 Hz | $z{min} f_s / 2$ | | ZCR upper bound as a tone | $z_{max} f_s / 2$ = 2400 Hz | $z_{max} f_s / 2$ | | Frames | $M$ = 38 | $\lceil L / H \rceil$ |

Trade-offs

  • A lower threshold detects quieter speech but also classifies more background noise as speech.

  • Smoothing, hangover and minimum-run rules remove rapid switching between speech and silence but delay and stretch region boundaries by a few frames.

Warnings

  • Info: Frames are 64 ms long; speech VAD usually uses 10 to 30 ms frames, so short pauses will be missed. Hint: At 16000 Hz a 25 ms frame is 400 samples.

  • Info: The majority vote uses only past frames, so speech onsets are reported about 2 frame(s) late.

See also

  • Mask: audio_samples::AudioVoiceActivityDetection::voice_activity_mask

  • Mask (Python): audio_samples.AudioSamples.voice_activity_mask

  • Regions: audio_samples::AudioVoiceActivityDetection::speech_regions

  • Regions (Python): audio_samples.AudioSamples.speech_regions

  • Python: audio_samples.VadConfig.explain

assert doc.quantity("Frame duration") == 64.0  # 1024 / 16 kHz, in ms
assert doc.quantity("ZCR lower bound as a tone") == 160.0  # 0.02 x 8 kHz
assert doc.quantity("ZCR upper bound as a tone") == 2_400.0  # 0.30 x 8 kHz
assert doc.has_warning_containing("64 ms")

speech_cfg = vad_config(frame_size=400, hop_size=160)
doc2 = audio.explain(speech_cfg)  # the signal supplies fs and the length
assert doc2.quantity("Frame duration") == 25.0
assert doc2.quantity("Hangover") == 20.0  # 2 frames x 10 ms
assert doc2.quantity("Frames") == 120.0

Exercises

1. Levels. Predict the RMS level in dBFS of (a) a full-scale sine and (b) white_noise with amplitude 0.1 (uniform on \([-0.1, 0.1)\)). Check with AudioSamples.rms(). Put the two measured levels in answer as a tuple.

answer = None  # TODO
# Solution
sine = aus.sine_wave(1_000.0, 1.0, sample_rate=16_000, amplitude=1.0, dtype=F64)
noise = aus.white_noise(1.0, sample_rate=16_000, amplitude=0.1, dtype=F64, seed=7)
answer = (20 * np.log10(sine.rms()), 20 * np.log10(noise.rms()))
assert abs(answer[0] - 20 * np.log10(1 / np.sqrt(2))) < 1e-3  # -3.01 dB; whole periods: exact
# Uniform noise has RMS a / sqrt(3): -24.77 dBFS. 16000 random samples estimate it to about
# 1 % (0.1 dB).
assert abs(answer[1] + 24.77) < 0.1

2. Hangover. With the energy VAD above, predict how far the end of the speech region moves when the hangover goes from 1 to 6 frames. Put the end sample with 6 frames in answer.

answer = None  # TODO
# Solution
def end(h):
    c = vad_config(aus.VadMethod.energy, frame_size=400, hop_size=160, energy_threshold_db=-40.0,
                   smooth_frames=1, min_speech_frames=0, min_silence_frames=0, hangover_frames=h)
    return audio.speech_regions(c)[0][1]

answer = end(6)
# Each extra hangover frame keeps one more 10 ms frame active: 5 x 160 = 800 samples later.
assert end(1) == 14_960 and answer == 15_760 and answer - end(1) == 5 * 160

3. A loud hum. A 100 Hz tone at \(-10\) dBFS peak is not speech. Predict its per-sample ZCR, then decide which rule rejects it: energy or combined. Put the number of active frames under the combined rule in answer.

answer = None  # TODO
# Solution
amp = 10 ** (-10 / 20)  # -10 dBFS peak, -13 dBFS RMS
hum = aus.sine_wave(100.0, 0.5, sample_rate=16_000, amplitude=amp, dtype=F64)
assert abs(20 * np.log10(hum.rms()) + 13.01) < 0.01
h = hum.to_numpy()[1_000:1_400]
z = np.count_nonzero((h[1:] > 0) != (h[:-1] > 0)) / 399
assert abs(z - 2 * 100 / 16_000) < 0.003  # 0.0125: 5 crossings in 400 samples
count = lambda m: int(np.sum(hum.voice_activity_mask(
    vad_config(m, frame_size=400, hop_size=160, energy_threshold_db=-40.0))))
assert count(aus.VadMethod.energy) > 0  # loud enough to pass the energy rule
answer = count(aus.VadMethod.combined)
assert answer == 0  # z < z_min = 0.02: rejected

Common pitfalls

  • Units of ZCR. The VAD uses crossings per sample (per frame); zero_crossing_rate() returns crossings per second for the whole signal; zero_crossing_rate_frames() returns a per-frame fraction (crossings / frame length, centred frames by default). Divide by \(f_s\) to compare.

  • dBFS conventions. Levels here are RMS levels (dBFS RMS), so a full-scale sine is \(-3.01\) dBFS; where a peak level is meant it is written “dBFS peak” (exercise 3). AES17 calibrates RMS levels so that a full-scale sine reads 0 dBFS.

  • Default frames are long. VadConfig.default() uses 1024 / 512 samples (64 / 32 ms at 16 kHz); speech VAD normally uses 20-30 ms frames.

  • Fricatives fail the combined rule. /s/ and /f/ have speech-like energy but noise-like ZCR, so the default ZCR window (0.02-0.30) drops them. Use the energy rule with hangover if you need whole words.

  • Smoothing delays onsets. The majority vote looks only backwards, so onsets are reported about \((S - 1)/2\) frames late; hangover delays offsets.

  • Regions are wider than the speech. A region starts at the first frame touching speech and ends at the end of the first inactive frame.

See also

References

  • Rabiner, L. R. and Sambur, M. R. (1975). An algorithm for determining the endpoints of isolated utterances. Bell System Technical Journal, 54(2), 297-315. (Energy plus zero-crossing-rate endpoint detection.)

  • Rabiner, L. R. and Schafer, R. W. (1978). Digital Processing of Speech Signals. Prentice-Hall. Chapter 4 (short-time energy and zero-crossing rate).