/** * Finds stretches of speech in a continuous microphone stream, by loudness alone. * * Pure: no clock (time is counted in samples), no I/O. It is not a speech recogniser and does * not know words; it only decides "someone started talking" and "they stopped", so that the * app can send one utterance at a time instead of a never-ending stream. * * Audio is 16 kHz signed 16-bit little-endian mono (the only format the app handles). It is * examined in 20 ms windows. A window is "voiced" when its level is clearly above the * background, which is tracked continuously while nobody is speaking. * * NOT device-tested: the thresholds are first guesses for a microphone whose levels have not * been measured (see docs/device-test-plan.md). */ export interface SegmenterOptions { /** A pause this long ends the utterance. */ endSilenceMs: number; /** Less voiced sound than this in total is a click or a cough, not an utterance. */ minSpeechMs: number; /** Audio kept from just before speech was detected, so the first syllable is not clipped. */ prerollMs: number; /** An utterance is cut off (and still delivered) at this length. */ maxMs: number; /** A window is never voiced below this RMS level (full scale is 32768). */ minRms: number; /** A window is voiced when its level is at least this many times the background level. */ ratio: number; } export const WAKE_SEGMENTER: SegmenterOptions = { endSilenceMs: 700, minSpeechMs: 240, prerollMs: 400, maxMs: 30_000, minRms: 260, ratio: 3, }; export type SegmentEvent = | { type: 'start' } /** The utterance, from the preroll to the end of the closing pause. */ | { type: 'end'; pcm: Uint8Array } /** What looked like speech was too short to be an utterance. */ | { type: 'discard' }; const WINDOW_BYTES = 640; // 20 ms const WINDOW_MS = 20; /** This many voiced windows in a row start an utterance. */ const ONSET_WINDOWS = 3; export class SpeechSegmenter { private options: SegmenterOptions; /** Bytes that do not yet fill a window. */ private carry = new Uint8Array(0); /** Recent windows while nobody is speaking: the preroll. */ private recent: Uint8Array[] = []; /** Windows of the utterance in progress. */ private speech: Uint8Array[] | null = null; private voicedRun = 0; private voicedWindows = 0; private silentRun = 0; private levelSum = 0; /** Background level, learned while nobody is speaking. */ private floor = 0; constructor(options: SegmenterOptions = WAKE_SEGMENTER) { this.options = options; } /** Someone is talking right now (an utterance has started and not yet ended). */ get speaking(): boolean { return this.speech !== null; } /** Change the timing rules from the next window on, without losing what has been heard. */ configure(options: SegmenterOptions): void { this.options = options; } /** Forget everything heard so far, keeping what was learned about the background level. */ reset(): void { this.carry = new Uint8Array(0); this.recent = []; this.speech = null; this.voicedRun = 0; this.voicedWindows = 0; this.silentRun = 0; this.levelSum = 0; } /** * Everything currently held: the utterance in progress, or else the preroll. Used when a * recording takes over from listening, so that what was already being said is not lost. */ buffered(): Uint8Array { return concat(this.speech ?? this.recent); } push(pcm: Uint8Array): SegmentEvent[] { const events: SegmentEvent[] = []; let data = pcm; if (this.carry.length) { data = new Uint8Array(this.carry.length + pcm.length); data.set(this.carry); data.set(pcm, this.carry.length); } let offset = 0; for (; offset + WINDOW_BYTES <= data.length; offset += WINDOW_BYTES) { this.window(data.slice(offset, offset + WINDOW_BYTES), events); } this.carry = data.slice(offset); return events; } private window(win: Uint8Array, events: SegmentEvent[]): void { const level = rms(win); const voiced = level >= Math.max(this.options.minRms, this.floor * this.options.ratio); if (!this.speech) { this.recent.push(win); const keep = Math.max(ONSET_WINDOWS, Math.ceil(this.options.prerollMs / WINDOW_MS)); if (this.recent.length > keep) this.recent.shift(); if (!voiced) { this.voicedRun = 0; // Follows a quieter room at once and a louder one slowly. this.floor = this.floor === 0 || level < this.floor ? level : this.floor * 0.98 + level * 0.02; return; } this.voicedRun += 1; if (this.voicedRun < ONSET_WINDOWS) return; this.speech = this.recent; this.recent = []; this.voicedWindows = this.voicedRun; this.voicedRun = 0; this.silentRun = 0; this.levelSum = 0; events.push({ type: 'start' }); return; } this.speech.push(win); this.levelSum += level; if (voiced) { this.voicedWindows += 1; this.silentRun = 0; } else { this.silentRun += 1; } const paused = this.silentRun * WINDOW_MS >= this.options.endSilenceMs; const tooLong = this.speech.length * WINDOW_MS >= this.options.maxMs; if (!paused && !tooLong) return; const speech = this.speech; const enough = this.voicedWindows * WINDOW_MS >= this.options.minSpeechMs; if (tooLong && !paused) { // Never a pause in all that time: this is a steady noise, not a voice. Treat its level as // the new background so the next thing delivered is something that stands out from it. this.floor = this.levelSum / speech.length; } this.speech = null; this.voicedWindows = 0; this.silentRun = 0; events.push(enough ? { type: 'end', pcm: concat(speech) } : { type: 'discard' }); } } function rms(win: Uint8Array): number { let sum = 0; const samples = win.length >> 1; for (let i = 0; i < samples; i++) { let v = win[2 * i]! | (win[2 * i + 1]! << 8); if (v & 0x8000) v -= 0x10000; sum += v * v; } return Math.sqrt(sum / samples); } function concat(chunks: Uint8Array[]): Uint8Array { let total = 0; for (const chunk of chunks) total += chunk.length; const out = new Uint8Array(total); let offset = 0; for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.length; } return out; }