Voice activity detection: speech evidence, state and timing
语音活动检测
Inspect an energy baseline and a streaming hysteresis machine; distinguish model windows, confirmed endpoints, padding and duration-weighted errors.
voice-activity-detectionA loud sound is not necessarily speech
Suppose a recorder should keep spoken instructions and skip the gaps between them. An energy threshold seems like a reasonable first attempt: keep loud frames, discard quiet ones. It immediately faces two counterexamples—a quiet instruction and a loud machine. Voice activity detection (VAD) asks whether speech is present, not merely whether a signal has energy.
VAD also differs from recognizing words, identifying a speaker and detecting vocal-fold periodicity. Unvoiced speech sounds still belong to speech. Some software uses “voiced/unvoiced” loosely for the VAD output; read it as the interface’s speech/non-speech decision rather than a complete phonetic classification. The WebRTC wrapper exposes a Boolean decision for an audio frame. Frame interface
The output may be a frame decision, a speech score or a list of speech intervals. Those representations need different timing rules. If a detector waits for several quiet frames before closing an interval, its reported end can precede the instant at which the decision becomes available. We will calculate that delay explicitly and keep the acoustic detector separate from its interval post-processing.
Features, decisions and intervals are separate layers
An energy baseline you can inspect
For sample rate and frame duration milliseconds, use samples when that length is an integer. Our frames do not overlap. A final short frame uses its actual length rather than silently adding zeros. With normalized samples , define mean-square energy and a sign-change rate:
The program defines for a one-sample frame. Zero crossing measures sign changes, not the presence of words. Constant and rapidly alternating signals can have identical energy while different sign-change rates; neither feature alone proves that a person spoke. The tutorial uses normalized floating-point samples, whereas the cited WebRTC wrapper’s interface expects 16-bit mono PCM. Input contract
Convert energy to a decibel scale with an explicit floor. If neither signal is on that floor, multiplying amplitude by changes energy level by :
Our baseline accepts at or above a threshold. Its zero-energy value is −120 dB because of the floor. Changing gain changes the decision unless the threshold or normalization also changes. This is an inspectable baseline, not a model of all speech and background sounds.
Statistical and neural detectors add acoustic evidence
The inspected WebRTC core models frequency-band features under noise and speech hypotheses with Gaussian mixtures. It combines approximate likelihood-ratio evidence and local band tests, updates internal models, and applies a hangover state. This is substantially more than the single energy threshold in our program. The following is a generic real-valued mixture score explaining the idea, not its fixed-point implementation:
Here indexes feature bands, mixture components, and mean noise and speech. Mixture weights are nonnegative and sum to one within each hypothesis/band; variances are positive. A likelihood ratio compares explanations of a feature, rather than interpreting its raw magnitude as speech. One inspected source comment mistakenly prints , but the subsequent derivation and code use the difference between speech and noise log evidence. WebRTC core and comment discrepancy
A neural detector instead learns acoustic features and a decision function from training data. Silero’s inspected utility obtains a speech score from each model window, then separately converts scores into intervals. Its wrapper resets model state for an offline call and uses 512 samples at 16 kHz or 256 at 8 kHz—32 ms in either case. These are that utility’s model windows, not the WebRTC frame contract of 10, 20 or 30 ms. Our code below supplies probabilities directly and runs no acoustic model. Model windows and post-processing WebRTC frame lengths
A score called a probability should not automatically be treated as calibrated for a new recording domain. Tune the downstream decision using held-out conditions representative of the task. A detector and a post-processor answer different questions: acoustic scoring estimates speech evidence; post-processing defines when to open, hold and close an interval.
Hysteresis stops a threshold from flickering
Use an onset threshold higher than an offset threshold . Basic hysteresis retains its previous active state in the middle band. Before adding duration constraints, its one-step rule can be written:
Our state machine extends this rule by requiring several consecutive low frames before closing. Inactive state opens only at or above the onset threshold. During activity, a frame below the offset threshold starts or extends a low run; any frame at or above the offset threshold clears that run. Thus an intermediate score keeps activity alive and interrupts the pending end. A confirmed interval is retained only when its length reaches the minimum speech duration.
Let be its start frame, the first frame in a confirmed low run and the required number of consecutive low frames. With fixed frame hop seconds, the interval ends at , but that decision becomes available after reading through the low run:
This is the post-processor’s waiting delay. Model lookahead, audio buffering and computation add other delays. At end of file, our implementation retains a short, unconfirmed low tail inside the active segment. A different end-of-stream policy can produce different boundaries and should be tested explicitly.
The fixed Silero routine is not identical to this teaching state machine. It clears a tentative end when a score returns to the higher threshold, uses a strict greater-than check for minimum speech length, and has additional maximum-duration branches. Its default low threshold is clipped at 0.01. Our code uses consecutive-low resetting, inclusive minimum length and no maximum-duration splitting; these choices are stated rather than disguised as library compatibility. Thresholds and interval rules
Padding and evaluation need their own definitions
To avoid cutting tight to a detected boundary, our optional padding expands each interval by frames, clips to a recording of frames, then takes the union. Touching or overlapping expansions merge:
Padding changes the returned intervals; it does not create new acoustic evidence. The inspected Silero routine apportions short gaps between neighbors rather than using this union rule, another deliberate difference. Evaluate the final interval output as well as the raw threshold decisions when padding matters to the application. Boundary padding
For reference speech indicator , predicted speech indicator and actual frame duration , count missed and falsely accepted time. Use separate denominators for reference speech and reference non-speech:
The final short frame matters: treating it as a full frame changes time weighting. An absent reference class makes its rate undefined, not automatically zero. Precision and recall answer different questions from the two class-conditional error rates. With denoting correctly detected speech time:
The program returns None for any zero denominator. State whether an evaluation is weighted by frames, duration or segments; these can reward different behavior. A detector that discards the beginning of every command may have a modest total missed duration while still damaging downstream recognition.
Run the baseline and stream the probabilities
Save the program as vad.py and run python vad.py using Python 3.12 and NumPy 1.26.4. It generates short synthetic signals and also accepts a separate supplied probability sequence. It contains no downloaded model, learned acoustic classifier or actual human-speech benchmark.
"""Original energy baseline and explicit streaming hysteresis; not Silero/WebRTC."""
import json
import numpy as np
def numeric(value):
return type(value) in (int,float) and np.isfinite(value)
def frame_features(samples,sample_rate=16000,frame_ms=20):
raw=np.asarray(samples)
if raw.ndim!=1 or raw.dtype.kind not in 'fiu':raise ValueError('Mono real sample vector required')
x=raw.astype(float)
if type(sample_rate) is not int or sample_rate not in (8000,16000,32000,48000):
raise ValueError('Supported sample rate required')
if type(frame_ms) is not int or frame_ms not in (10,20,30):raise ValueError('Use10/20/30ms nonoverlapping frames')
n=sample_rate*frame_ms//1000
if not 1<=len(x)<=sample_rate*2 or not np.isfinite(x).all() or np.max(abs(x))>1:
raise ValueError('At most2 seconds, finite normalized PCM within [-1,1]')
count=(len(x)+n-1)//n;energy=[];crossing=[];valid=[]
for t in range(count):
frame=x[t*n:min((t+1)*n,len(x))];valid.append(len(frame))
# Partial final frames use actual length; no silent zero-padding dilution.
energy.append(float(np.mean(frame**2)))
crossing.append(float(np.mean((frame[:-1]>=0)!=(frame[1:]>=0))) if len(frame)>1 else 0.)
return dict(energy=energy,db=[10*np.log10(max(e,1e-12)) for e in energy],
zero_crossing=crossing,valid_samples=valid,frame_samples=n,sample_rate=sample_rate)
def energy_mask(features,threshold_db=-30.):
if not numeric(threshold_db) or not -120<=threshold_db<=0:raise ValueError('Threshold in [-120,0] dB required')
return [bool(value>=threshold_db) for value in features['db']]
class Hysteresis:
def __init__(self,on=.6,off=.4,min_speech=2,min_silence=2):
if not numeric(on) or not numeric(off) or not 0<=off<on<=1:raise ValueError('Require0<=off<on<=1')
if type(min_speech) is not int or type(min_silence) is not int or not 1<=min_speech<=32 or not 1<=min_silence<=32:
raise ValueError('Durations must be1..32 complete frames')
self.on,self.off,self.min_speech,self.min_silence=on,off,min_speech,min_silence
self.reset()
def reset(self):
self.index=0;self.start=None;self.low=None;self.spans=[];self.events=[];self.finished=False
def _close(self,end,detected):
keep=end-self.start>=self.min_speech
self.events.append(dict(start=self.start,end=end,detected_at=detected,kept=keep))
if keep:self.spans.append([self.start,end])
self.start=None;self.low=None
def feed(self,probabilities):
p=np.asarray(probabilities)
if self.finished:raise ValueError('Reset before a new stream')
if p.ndim!=1 or p.dtype.kind not in 'fiu' or not np.isfinite(p).all() or not ((p>=0)&(p<=1)).all() or self.index+len(p)>1024:
raise ValueError('At most1024 finite supplied probabilities in [0,1]')
for value in p:
t=self.index;self.index+=1
if self.start is None:
if value>=self.on:self.start=t
continue
if value<self.off:
if self.low is None:self.low=t
if self.index-self.low>=self.min_silence:self._close(self.low,self.index)
else:
# This toy requires consecutive low frames, unlike every library policy.
self.low=None
return [list(span) for span in self.spans]
def finish(self):
if not self.finished:
# A short unconfirmed low run at EOF remains inside the active segment.
if self.start is not None:self._close(self.index,self.index)
self.finished=True
return dict(spans=[list(s) for s in self.spans],events=[dict(e) for e in self.events],frames=self.index)
def padding(spans,total_frames,pad=1):
if type(total_frames) is not int or not 0<=total_frames<=1024 or type(pad) is not int or not 0<=pad<=32:
raise ValueError('Bounded frame count and padding required')
if not isinstance(spans,(list,tuple)):raise ValueError('Explicit frame intervals required')
merged=[];previous=0
for pair in spans:
if not isinstance(pair,(list,tuple)) or len(pair)!=2 or any(type(x) is not int for x in pair):raise ValueError('Integer frame boundaries required')
a,b=pair
if not previous<=a<b<=total_frames:raise ValueError('Sorted disjoint intervals required')
previous=b;a=max(0,a-pad);b=min(total_frames,b+pad)
if merged and a<=merged[-1][1]:merged[-1][1]=max(merged[-1][1],b)
else:merged.append([a,b])
return merged
def frame_metrics(reference,prediction,durations):
r,p=np.asarray(reference),np.asarray(prediction);w=np.asarray(durations)
if r.ndim!=1 or p.shape!=r.shape or w.shape!=r.shape or not 1<=len(r)<=1024 or r.dtype.kind!='b' or p.dtype.kind!='b' or w.dtype.kind not in 'fiu':
raise ValueError('Matching Boolean frame labels and positive durations required')
if not np.isfinite(w).all() or not ((w>0)&(w<=1)).all():raise ValueError('Frame durations in (0,1] seconds')
tp=float(w[r&p].sum());fn=float(w[r&~p].sum());fp=float(w[~r&p].sum());tn=float(w[~r&~p].sum())
return dict(true_positive=tp,miss=fn,false_alarm=fp,true_negative=tn,
miss_rate=fn/(tp+fn) if tp+fn else None,false_alarm_rate=fp/(fp+tn) if fp+tn else None,
precision=tp/(tp+fp) if tp+fp else None,recall=tp/(tp+fn) if tp+fn else None)
def demo():
fs=16000;n=320;t=np.arange(n)/fs;tone=np.sin(2*np.pi*1000*t)
x=np.concatenate([np.zeros(n),.01*tone,.1*tone,.1*np.sign(tone),np.zeros(n//2)])
features=frame_features(x);mask=energy_mask(features)
probs=[.1,.7,.55,.2,.5,.7,.2,.1,.65,.2,.1,.2]
machine=Hysteresis();machine.feed(probs);state=machine.finish();padded=padding(state['spans'],len(probs))
chunked=Hysteresis()
for a,b in [(0,3),(3,7),(7,len(probs))]:chunked.feed(probs[a:b])
return dict(features=features,energy_mask=mask,energy_metrics=frame_metrics([False,True,True,False,False],mask,np.array(features['valid_samples'])/fs),
probabilities=probs,segmentation=state,chunked=chunked.finish(),padded=padded,
scope='Synthetic amplitudes and assigned labels plus supplied probabilities; not actual speech detection accuracy.')
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
The signal example has silence, a quiet sinusoid, a louder sinusoid, a square-like signal and a short final silence. Its assigned speech/non-speech labels deliberately make quiet energy a miss and loud non-speech energy a false alarm. Under the chosen threshold, duration-weighted miss rate is 0.5 and false-alarm rate is 0.4. Those numbers describe this constructed counterexample only.
The probability example uses [.1,.7,.55,.2,.5,.7,.2,.1,.65,.2,.1,.2], onset 0.6, offset 0.4, and minimum speech/silence lengths of two frames. The short low dip at index 3 is cancelled by the intermediate score at index 4. The two low frames starting at index 6 confirm interval [1,6) after frame 7 has been read, so detected_at is 8. A later [8,9) interval is discarded as too short. Padding by one frame gives [0,7).
Feed the same probabilities in pieces. Every split point must produce the same final intervals and events as a single call, provided the state is retained. finish is idempotent, and a new stream requires reset. The implementation validates an entire incoming probability batch before advancing, so an invalid later value does not partly consume the batch.
Feature extraction takes time for samples and stores frame summaries. Post-processing takes time with constant core state, plus possible saved events. Padding sorted disjoint intervals takes time. Frame-level scoring takes time. These costs exclude any acoustic model, and the interval state machine is bounded to 1,024 input frames for this exercise.
Measure what the downstream task needs
Energy can help distinguish activity from silence under controlled conditions, but it cannot establish that activity is speech. Additional band structure, temporal context or learned features can provide more evidence; they also introduce parameters, data requirements and state that need their own validation. The WebRTC statistical core and Silero post-processing are useful references precisely because they expose mechanisms absent from the elementary baseline. Statistical detector Neural-output processing
Choose frame-level metrics and boundary metrics that reflect the use case. An archival segmenter may tolerate delay but need complete utterances. An interactive system may need a quick endpoint and a way to recover when speech resumes. These are different objective choices; one aggregate score cannot determine the right minimum silence, padding and onset threshold.
Check short speech, long gaps, equality at thresholds, changing sample rates, final partial frames and end-of-stream behavior. Keep calibration/development recordings separate from final evaluation. The toy code’s clean chunking result proves its own state logic, not that restarting a real neural model at arbitrary chunks is safe. The inspected offline Silero helper explicitly resets its model, so invoking that helper separately on every chunk changes the computation. Offline reset and inference loop
To connect sample count to time and amplitude units, see audio signal fundamentals. VAD can help prepare audio for later recognition or diarization, but it supplies neither words nor speaker identity by itself.
Test the edges of the state machine
-
Two frames have identical mean-square energy. One is labeled speech in a teaching dataset, the other non-speech. Can an energy-only threshold classify both correctly?
Answer: No. Their identical feature gives the same threshold decision. More elaborate timing cannot recover an acoustic distinction that is absent from the supplied feature without other information. This is why the synthetic example includes a loud non-speech counterexample.
-
Inactive state receives 0.6 with onset threshold 0.6. Later, active state receives 0.4 with offset threshold 0.4. Does the first open speech, and does the second start a low run?
Answer: The first opens speech because onset uses
>=. The second does not start a low run because offset uses strict<; it clears any pending consecutive-low run in this implementation. Equality rules are part of the algorithm. -
The first confirmed low frame has index 6, two low frames are required, and the hop is 20 ms. What end time is reported, and when is the decision available?
Answer: Reported end is ms. After reading frames 6 and 7, the decision is available at ms, a 40 ms wait. Add any acoustic-model and device delay separately; the frame hop alone is not total latency.
-
A recording ends after one low frame, fewer than the two needed to close activity. What does our
finishdo, and would resetting at every chunk preserve the result?Answer: It keeps the unconfirmed low tail inside the active interval, then applies the minimum speech-length rule. Resetting each chunk would lose pending activity and can change boundaries. Preserve state across chunks, flush only at the real end, and reset for a new stream.
Compare contracts before comparing detector names
The WebRTC wrapper specifies input formats and supported frame lengths; its core implements bandwise statistical decisions and state. Silero’s utility shows how model windows and scores become intervals. Read those contracts before assuming that two functions called VAD use identical timing or thresholds. Our original baseline and state machine are independently checked components with explicit differences, not rebranded versions of either detector. WebRTC interface WebRTC core Silero utility
Make a prediction, then check
The first low frame is6, two lows are required, and hop is20ms. When is the end reported and the decision available?
Learning objectives
- Explain why energy alone cannot establish speech.
- Separate acoustic scores from interval post-processing.
- Trace threshold equalities, consecutive lows, EOF and reset.
- Compute decision delay and errors using actual frame duration.
Prerequisites & connections
Explore related knowledge →References
- py-webrtcvad: frame interface at e283ca4
John Wiseman and py-webrtcvad contributors - WebRTC VAD core vendored in py-webrtcvad at e283ca4
wiseman/py-webrtcvad contributors - Silero VAD utility at867c2aa
snakers4/silero-vad contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked normalized energy and zero-crossings, actual partial frames, WebRTC GMM hypothesis versus implementation approximations, supplied-score hysteresis, minimum lengths, EOF/reset and padding, and duration-weighted metrics against scoped fixed WebRTC/Silero source. Eight paired equations and four explained exercises. Explicit boundary and state differences from Silero; synthetic probabilities without acoustic inference or measured VAD accuracy.
- Verified energy/gain and actual partial-frame duration, threshold equality, all chunk boundaries, reset/EOF, kept interval[1,6) confirmed at8, discarded short event, padded[0,7), synthetic miss0.5 and false alarm0.4.
- Four computed SVGs bind exact bilingual MDX. The three-topic group passed ten numeric/encoding checks and 18 isolated language/width cases with four fallback fonts; six representative final screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- py-webrtcvad: frame interface at e283ca4 · Read README1–55 plus cached C API82–116 for16-bit mono PCM, rates and10/20/30ms frames. Full55-line license distinguishes MIT wrapper and BSD WebRTC code. Original float baseline is not library inference.
- WebRTC VAD core vendored in py-webrtcvad at e283ca4 · Read175–255 band GMM/approximate likelihood and452–488 constraints/hangover, plus limited parameter locations. CommentH1/H1 conflicts with the subsequent H1/H0 computation. Full adaptation/filter implementation not replicated.
- Silero VAD utility at867c2aa · Read225–365 and404–465: arguments, model reset/window, opening/closing, minimum durations, EOF and padding. Maximum-duration middle branches, model wrapper and VADIterator not fully read. Our consecutive-low reset/inclusive length/union padding are different. MIT license read; no neural model run.
Related topics