File size: 2,329 Bytes
75639c0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | """Streaming voice activity detection with stream-vad-small (ONNX, CPU). pip install onnxruntime soundfile numpy
python example.py audio.wav → prints speech segments (start, end) in seconds
Audio must be 16 kHz mono float32. Feed any multiple of 160 samples per call (10 ms frames); 480 (30 ms) is a good default."""
import sys, numpy as np, onnxruntime as ort, soundfile as sf
class StreamVAD:
def __init__(self, path="stream-vad-small.onnx", threads=1):
so = ort.SessionOptions(); so.intra_op_num_threads = threads
self.sess = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"]); self.reset()
def reset(self): # call at the start of every new stream
self.state = [np.zeros((1, 96), np.float32), np.zeros((1, 40, 4), np.float32),
np.zeros((1, 128, 4), np.float32), np.zeros((1, 1, 128), np.float32)]
def __call__(self, chunk): # chunk: float32 array, len % 160 == 0 → speech probability per 10 ms frame
out = self.sess.run(None, dict(zip(["audio", "ctx_audio", "ctx_c1", "ctx_c2", "h"], [chunk[None].astype(np.float32), *self.state])))
self.state = out[1:]; return out[0][0]
def segments(probs, on=0.5, off=0.35, min_speech=0.25, min_silence=0.3, pad=0.05):
"""10 ms probabilities → [(start_s, end_s)] with hysteresis and minimum durations."""
segs, start, below = [], None, 0
for i, p in enumerate(probs):
if start is None:
if p >= on: start, below = i, 0
elif p < off:
below += 1
if below * 0.01 >= min_silence:
end = i - below + 1
if (end - start) * 0.01 >= min_speech: segs.append((start, end))
start = None
else: below = 0
if start is not None and (len(probs) - start) * 0.01 >= min_speech: segs.append((start, len(probs)))
return [(max(0.0, a * 0.01 - pad), b * 0.01 + pad) for a, b in segs]
if __name__ == "__main__":
x, sr = sf.read(sys.argv[1], dtype="float32", always_2d=True); x = x[:, 0]
assert sr == 16000, "resample to 16 kHz first"
vad, probs = StreamVAD(), []
for i in range(0, len(x) - 479, 480): probs.append(vad(x[i:i + 480])) # 30 ms chunks, as a live stream would arrive
for a, b in segments(np.concatenate(probs)): print(f"{a:8.2f} {b:8.2f}")
|