mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(stt): add energy-based VAD with silence gate and auto-stop (#249)
* loop: stt-warmup completed after 6 iterations
* refactor: extract STT startup helpers and simplify audio recorder
* feat(stt): add energy-based VAD with silence gate and auto-stop
- New VoiceActivityDetector class: adaptive noise floor, per-frame RMS
classification, trailing-silence endpointing, configurable thresholds
- AudioWorkletProcessor computes RMS in existing flush loop and posts
{samples, rms} instead of a bare Int16Array
- AudioRecorder integrates VAD via handleVadFrame() in both worklet and
ScriptProcessor paths; auto-calls stop() on trailing silence; silence
gate in processRecording() fires onNoSpeech instead of sending empty
audio to the transcription API (fixes Whisper hallucination bug)
- useSTT wires setOnNoSpeech to reset isProcessing/isRecording cleanly
without surfacing an error
- computeRms() exported helper for ScriptProcessor fallback path
* fix(stt): clear processing state when stopping a silent recording
stopRecording() called recorder.stop() before setIsProcessing(true). For
a silent take the recorder synchronously fires onNoSpeech (which sets
processing false), so the subsequent setIsProcessing(true) won and the
voice overlay was stuck in the processing state forever.
Set processing before stop() so the recorder callback (onNoSpeech or
onDataAvailable) has the final say on the processing flag.
* fix(stt): always emit a terminal signal so the voice overlay never sticks
Two remaining stuck paths after the silent-stop fix:
- processRecording() early-returned without firing onNoSpeech when a take
had no captured audio (e.g. a quick start/stop under one worklet flush,
totalSamples === 0). Now any non-emitting path (empty audio or no
detected speech) fires onNoSpeech, while a genuine abort still returns
silently.
- stopRecording() set isProcessing true even when the recorder was no
longer recording (double-stop or post auto-stop), where stop() skips
processRecording entirely and nothing clears the flag. Guard the
external path on recorder state before entering processing.
* loop: mediarecorder-stt completed after 6 iterations
* refactor(stt): extract shared helpers and cleanup
* refactor(stt): add separate arm/disarm thresholds for voice swipe
* fix(stt): prevent default touch behavior on voice gesture handlers
* feat(stt): add audio-level speech detection before emitting data
This commit is contained in:
1 parent
ab624a0970
commit
2b2cb6d23d
13 files changed
+1625
-549
No files matched your search
@@ -1,160 +1,514 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AudioRecorder, downsampleAndConvert, encodeWavFromInt16 } from './audioRecorder'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { waitFor } from '@testing-library/react'
|
||||
import { AudioRecorder } from './audioRecorder'
|
||||
|
||||
const blobToArrayBuffer = (blob: Blob): Promise<ArrayBuffer> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as ArrayBuffer)
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsArrayBuffer(blob)
|
||||
})
|
||||
class FakeMediaRecorder {
|
||||
static _instances: FakeMediaRecorder[] = []
|
||||
static _supportedTypes = new Set<string>([
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
])
|
||||
|
||||
describe('downsampleAndConvert', () => {
|
||||
it('should produce correct output length for 48kHz to 16kHz', () => {
|
||||
const inputLength = 4800
|
||||
const input = new Float32Array(inputLength)
|
||||
const output = downsampleAndConvert(input, 48000, 16000)
|
||||
|
||||
const expectedLength = Math.floor(inputLength * 16000 / 48000)
|
||||
expect(output.length).toBe(expectedLength)
|
||||
expect(output.length).toBe(inputLength / 3)
|
||||
})
|
||||
static isTypeSupported(type: string): boolean {
|
||||
return FakeMediaRecorder._supportedTypes.has(type)
|
||||
}
|
||||
|
||||
it('should produce correct output length for 44.1kHz to 16kHz', () => {
|
||||
const inputLength = 4410
|
||||
const input = new Float32Array(inputLength)
|
||||
const output = downsampleAndConvert(input, 44100, 16000)
|
||||
|
||||
const expectedLength = Math.floor(inputLength * 16000 / 44100)
|
||||
expect(output.length).toBeCloseTo(expectedLength, 0)
|
||||
})
|
||||
state: 'inactive' | 'recording' = 'inactive'
|
||||
stream: MediaStream
|
||||
mimeType: string
|
||||
ondataavailable: ((event: BlobEvent) => void) | null = null
|
||||
onstop: (() => void) | null = null
|
||||
onerror: ((event: Event) => void) | null = null
|
||||
|
||||
it('should clamp values in range [-1, 1] to Int16 range', () => {
|
||||
const input = new Float32Array([1.0, -1.0, 0.5, -0.5, 0.0])
|
||||
const output = downsampleAndConvert(input, 16000, 16000)
|
||||
|
||||
expect(output[0]).toBe(32767)
|
||||
expect(output[1]).toBe(-32768)
|
||||
expect(output[2]).toBeCloseTo(16383, 0)
|
||||
expect(output[3]).toBeCloseTo(-16384, 0)
|
||||
expect(output[4]).toBe(0)
|
||||
})
|
||||
constructor(stream: MediaStream, options?: MediaRecorderOptions) {
|
||||
this.stream = stream
|
||||
this.mimeType = options?.mimeType ?? ''
|
||||
FakeMediaRecorder._instances.push(this)
|
||||
}
|
||||
|
||||
it('should clamp values outside [-1, 1] range', () => {
|
||||
const input = new Float32Array([1.5, -1.5, 2.0, -2.0])
|
||||
const output = downsampleAndConvert(input, 16000, 16000)
|
||||
|
||||
expect(output[0]).toBe(32767)
|
||||
expect(output[1]).toBe(-32768)
|
||||
expect(output[2]).toBe(32767)
|
||||
expect(output[3]).toBe(-32768)
|
||||
})
|
||||
start(): void {
|
||||
this.state = 'recording'
|
||||
}
|
||||
|
||||
it('should return Int16Array type', () => {
|
||||
const input = new Float32Array(100)
|
||||
const output = downsampleAndConvert(input, 48000, 16000)
|
||||
|
||||
expect(output instanceof Int16Array).toBe(true)
|
||||
})
|
||||
})
|
||||
stop(): void {
|
||||
this.state = 'inactive'
|
||||
this.onstop?.()
|
||||
}
|
||||
}
|
||||
|
||||
describe('encodeWavFromInt16', () => {
|
||||
it('should create a Blob with audio/wav type', () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
|
||||
expect(blob.type).toBe('audio/wav')
|
||||
})
|
||||
function createMockTrack(): MediaStreamTrack {
|
||||
return { stop: vi.fn(), kind: 'audio' } as unknown as MediaStreamTrack
|
||||
}
|
||||
|
||||
it('should have RIFF header at offset 0', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const riff = String.fromCharCode(
|
||||
view.getUint8(0),
|
||||
view.getUint8(1),
|
||||
view.getUint8(2),
|
||||
view.getUint8(3)
|
||||
)
|
||||
expect(riff).toBe('RIFF')
|
||||
})
|
||||
|
||||
it('should have WAVE identifier at offset 8', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const wave = String.fromCharCode(
|
||||
view.getUint8(8),
|
||||
view.getUint8(9),
|
||||
view.getUint8(10),
|
||||
view.getUint8(11)
|
||||
)
|
||||
expect(wave).toBe('WAVE')
|
||||
})
|
||||
|
||||
it('should have sample rate at offset 24', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const sampleRate = view.getUint32(24, true)
|
||||
expect(sampleRate).toBe(16000)
|
||||
})
|
||||
|
||||
it('should have data identifier at offset 36', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const data = String.fromCharCode(
|
||||
view.getUint8(36),
|
||||
view.getUint8(37),
|
||||
view.getUint8(38),
|
||||
view.getUint8(39)
|
||||
)
|
||||
expect(data).toBe('data')
|
||||
})
|
||||
|
||||
it('should have correct file size for 1000 samples', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
|
||||
expect(arrayBuffer.byteLength).toBe(44 + 1000 * 2)
|
||||
})
|
||||
|
||||
it('should handle different sample rates', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 44100, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const sampleRate = view.getUint32(24, true)
|
||||
expect(sampleRate).toBe(44100)
|
||||
})
|
||||
|
||||
it('should handle stereo channels', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 2)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const channels = view.getUint16(22, true)
|
||||
expect(channels).toBe(2)
|
||||
})
|
||||
})
|
||||
function createMockStream(tracks: MediaStreamTrack[] = [createMockTrack()]): MediaStream {
|
||||
return {
|
||||
getTracks: () => tracks,
|
||||
getAudioTracks: () => tracks.filter(t => t.kind === 'audio'),
|
||||
getVideoTracks: () => [],
|
||||
addTrack: vi.fn(),
|
||||
removeTrack: vi.fn(),
|
||||
clone: vi.fn(),
|
||||
getTrackById: vi.fn(),
|
||||
active: true,
|
||||
id: 'mock-stream',
|
||||
onaddtrack: null,
|
||||
onremovetrack: null,
|
||||
} as unknown as MediaStream
|
||||
}
|
||||
|
||||
describe('AudioRecorder.isSupported', () => {
|
||||
it('should return boolean without throwing', () => {
|
||||
expect(() => {
|
||||
const result = AudioRecorder.isSupported()
|
||||
expect(typeof result).toBe('boolean')
|
||||
}).not.toThrow()
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
delete (Blob.prototype as { arrayBuffer?: unknown }).arrayBuffer
|
||||
})
|
||||
|
||||
it('returns true when navigator.mediaDevices.getUserMedia and window.MediaRecorder exist', () => {
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: vi.fn() },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
expect(AudioRecorder.isSupported()).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when navigator.mediaDevices.getUserMedia is missing', () => {
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: {},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
expect(AudioRecorder.isSupported()).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when window.MediaRecorder is undefined', () => {
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: vi.fn() },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: undefined,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
expect(AudioRecorder.isSupported()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder start', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let mockStream: MediaStream
|
||||
let recorder: AudioRecorder
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
let onError: ReturnType<typeof vi.fn>
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onNoSpeech: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set([
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockStream = createMockStream([mockTrack])
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(mockStream)
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onStateChange = vi.fn()
|
||||
onError = vi.fn()
|
||||
onDataAvailable = vi.fn()
|
||||
onNoSpeech = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
recorder.setOnError(onError)
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnNoSpeech(onNoSpeech)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('requests microphone with echoCancellation, noiseSuppression, and autoGainControl', async () => {
|
||||
await recorder.start()
|
||||
expect(mockGetUserMedia).toHaveBeenCalledWith({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('selects the first supported MIME type from the preferred list', async () => {
|
||||
await recorder.start()
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('audio/webm;codecs=opus')
|
||||
})
|
||||
|
||||
it('selects a lower-priority MIME when higher ones are unsupported', async () => {
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/ogg;codecs=opus'])
|
||||
await recorder.start()
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('audio/ogg;codecs=opus')
|
||||
})
|
||||
|
||||
it('constructs MediaRecorder without options when no MIME type is supported', async () => {
|
||||
FakeMediaRecorder._supportedTypes = new Set()
|
||||
await recorder.start()
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('')
|
||||
})
|
||||
|
||||
it('transitions to recording state', async () => {
|
||||
await recorder.start()
|
||||
expect(recorder.getState()).toBe('recording')
|
||||
expect(onStateChange).toHaveBeenCalledWith('recording')
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('AudioRecorder stop', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let mockStream: MediaStream
|
||||
let recorder: AudioRecorder
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onNoSpeech: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/webm;codecs=opus'])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockStream = createMockStream([mockTrack])
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(mockStream)
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onStateChange = vi.fn()
|
||||
onDataAvailable = vi.fn()
|
||||
onNoSpeech = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnNoSpeech(onNoSpeech)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('emits one combined blob via setOnDataAvailable and transitions to stopped', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
const chunk1 = new Blob(['part1'], { type: 'audio/webm;codecs=opus' })
|
||||
const chunk2 = new Blob(['part2'], { type: 'audio/webm;codecs=opus' })
|
||||
mr.ondataavailable?.({ data: chunk1 } as BlobEvent)
|
||||
mr.ondataavailable?.({ data: chunk2 } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('stopped')
|
||||
expect(onStateChange).toHaveBeenCalledWith('stopped')
|
||||
|
||||
expect(onDataAvailable).toHaveBeenCalledTimes(1)
|
||||
const emittedBlob = onDataAvailable.mock.calls[0][0] as Blob
|
||||
expect(emittedBlob).toBeInstanceOf(Blob)
|
||||
expect(emittedBlob.type).toBe('audio/webm;codecs=opus')
|
||||
})
|
||||
|
||||
it('stops all tracks after stopping', async () => {
|
||||
const track2 = createMockTrack()
|
||||
const stream2 = createMockStream([mockTrack, track2])
|
||||
mockGetUserMedia.mockResolvedValue(stream2)
|
||||
|
||||
await recorder.start()
|
||||
recorder.stop()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalledTimes(1)
|
||||
expect(track2.stop).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does nothing when not recording', async () => {
|
||||
recorder.stop()
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
expect(onNoSpeech).not.toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('idle')
|
||||
})
|
||||
|
||||
it('uses first chunk type as fallback when no MIME type is configured or available', async () => {
|
||||
FakeMediaRecorder._supportedTypes = new Set()
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('')
|
||||
|
||||
const chunk1 = new Blob(['audio-data'], { type: 'audio/ogg' })
|
||||
mr.ondataavailable?.({ data: chunk1 } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
expect(onDataAvailable).toHaveBeenCalledTimes(1)
|
||||
const emittedBlob = onDataAvailable.mock.calls[0][0] as Blob
|
||||
expect(emittedBlob.type).toBe('audio/ogg')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder no-speech', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let recorder: AudioRecorder
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onNoSpeech: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(async () => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/webm;codecs=opus'])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(createMockStream([mockTrack]))
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onDataAvailable = vi.fn()
|
||||
onNoSpeech = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnNoSpeech(onNoSpeech)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('calls setOnNoSpeech when no chunks were collected', async () => {
|
||||
await recorder.start()
|
||||
recorder.stop()
|
||||
|
||||
expect(onNoSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls setOnNoSpeech when the combined blob is zero size', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob([], { type: 'audio/webm;codecs=opus' }) } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
expect(onNoSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls setOnNoSpeech when decoded audio has no energy', async () => {
|
||||
class FakeAudioContext {
|
||||
decodeAudioData = vi.fn().mockResolvedValue({
|
||||
numberOfChannels: 1,
|
||||
getChannelData: () => new Float32Array([0, 0, 0, 0]),
|
||||
})
|
||||
|
||||
close = vi.fn().mockResolvedValue(undefined)
|
||||
}
|
||||
|
||||
Object.defineProperty(window, 'AudioContext', {
|
||||
value: FakeAudioContext,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(Blob.prototype, 'arrayBuffer', {
|
||||
value: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
|
||||
configurable: true,
|
||||
})
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob(['encoded-silence'], { type: 'audio/webm;codecs=opus' }) } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
await waitFor(() => expect(onNoSpeech).toHaveBeenCalledTimes(1))
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder abort and dispose', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let recorder: AudioRecorder
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(async () => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/webm;codecs=opus'])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(createMockStream([mockTrack]))
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onDataAvailable = vi.fn()
|
||||
onStateChange = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('abort stops tracks and transitions to idle', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob(['audio-data']) } as BlobEvent)
|
||||
|
||||
recorder.abort()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalled()
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('idle')
|
||||
})
|
||||
|
||||
it('dispose stops tracks and transitions to idle', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob(['audio-data']) } as BlobEvent)
|
||||
|
||||
recorder.dispose()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalled()
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('idle')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder error handling', () => {
|
||||
let recorder: AudioRecorder
|
||||
let onError: ReturnType<typeof vi.fn>
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: vi.fn() },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onError = vi.fn()
|
||||
onStateChange = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnError(onError)
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('maps NotAllowedError to Microphone permission denied', async () => {
|
||||
const error = new DOMException('Permission denied', 'NotAllowedError')
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('Microphone permission denied')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('maps NotFoundError to No microphone found', async () => {
|
||||
const error = new DOMException('No device found', 'NotFoundError')
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('No microphone found')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('maps other DOMException to formatted message', async () => {
|
||||
const error = new DOMException('Something else', 'SecurityError')
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('Microphone error: Something else')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('maps non-DOMException errors to Failed to start recording', async () => {
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('Failed to start recording')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('transitions to error state on microphone failure', async () => {
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(new Error('fail'))
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onStateChange).toHaveBeenCalledWith('error')
|
||||
})
|
||||
})
|
||||
+150
-174
@@ -1,104 +1,76 @@
|
||||
export type AudioRecorderState = 'idle' | 'recording' | 'stopped' | 'error'
|
||||
|
||||
export interface AudioRecorderOptions {
|
||||
sampleRate?: number
|
||||
channelCount?: number
|
||||
const DEFAULT_AUDIO_CONSTRAINTS: MediaTrackConstraints = {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
}
|
||||
|
||||
const DEFAULT_OPTIONS: AudioRecorderOptions = {
|
||||
sampleRate: 16000,
|
||||
channelCount: 1,
|
||||
const PREFERRED_MIME_TYPES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/ogg',
|
||||
'audio/mp4',
|
||||
'audio/wav',
|
||||
]
|
||||
const SPEECH_RMS_THRESHOLD = 0.005
|
||||
const SPEECH_PEAK_THRESHOLD = 0.02
|
||||
|
||||
type AudioContextConstructor = new () => AudioContext
|
||||
|
||||
function selectMimeType(): string | undefined {
|
||||
return PREFERRED_MIME_TYPES.find(type => MediaRecorder.isTypeSupported(type))
|
||||
}
|
||||
|
||||
const workletModulePromises = new WeakMap<AudioContext, Promise<void>>()
|
||||
|
||||
function ensureWorkletLoaded(ctx: AudioContext): Promise<void> {
|
||||
const existingPromise = workletModulePromises.get(ctx)
|
||||
|
||||
if (existingPromise) {
|
||||
return existingPromise
|
||||
}
|
||||
|
||||
const promise = ctx.audioWorklet.addModule('/audio-worklet-processor.js')
|
||||
workletModulePromises.set(ctx, promise)
|
||||
return promise
|
||||
function getAudioContextConstructor(): AudioContextConstructor | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
return window.AudioContext ?? (window as Window & { webkitAudioContext?: AudioContextConstructor }).webkitAudioContext ?? null
|
||||
}
|
||||
|
||||
export function downsampleAndConvert(input: Float32Array, inputRate: number, targetRate: number): Int16Array {
|
||||
const ratio = inputRate / targetRate
|
||||
const outputLength = Math.floor(input.length / ratio)
|
||||
const output = new Int16Array(outputLength)
|
||||
|
||||
for (let i = 0; i < outputLength; i++) {
|
||||
const index = i * ratio
|
||||
const prevIndex = Math.floor(index)
|
||||
const nextIndex = prevIndex + 1
|
||||
const t = index - prevIndex
|
||||
|
||||
let sample: number
|
||||
if (nextIndex >= input.length) {
|
||||
sample = input[prevIndex]
|
||||
} else {
|
||||
sample = input[prevIndex] * (1 - t) + input[nextIndex] * t
|
||||
async function blobHasSpeech(blob: Blob, AudioContextClass: AudioContextConstructor): Promise<boolean> {
|
||||
let context: AudioContext | null = null
|
||||
try {
|
||||
context = new AudioContextClass()
|
||||
const audioBuffer = await context.decodeAudioData(await blob.arrayBuffer())
|
||||
let peak = 0
|
||||
let sumSquares = 0
|
||||
let sampleCount = 0
|
||||
|
||||
for (let channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
|
||||
const samples = audioBuffer.getChannelData(channel)
|
||||
for (let i = 0; i < samples.length; i++) {
|
||||
const sample = samples[i]
|
||||
const amplitude = Math.abs(sample)
|
||||
peak = Math.max(peak, amplitude)
|
||||
sumSquares += sample * sample
|
||||
sampleCount++
|
||||
}
|
||||
}
|
||||
|
||||
const clamped = Math.max(-1, Math.min(1, sample))
|
||||
output[i] = clamped < 0 ? clamped * 32768 : clamped * 32767
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
export function encodeWavFromInt16(samples: Int16Array, sampleRate: number, channels: number): Blob {
|
||||
const dataLength = samples.length * 2
|
||||
const bufferSize = 44 + dataLength
|
||||
const buffer = new ArrayBuffer(bufferSize)
|
||||
const view = new DataView(buffer)
|
||||
|
||||
writeString(view, 0, 'RIFF')
|
||||
view.setUint32(4, 36 + dataLength, true)
|
||||
writeString(view, 8, 'WAVE')
|
||||
writeString(view, 12, 'fmt ')
|
||||
view.setUint32(16, 16, true)
|
||||
view.setUint16(20, 1, true)
|
||||
view.setUint16(22, channels, true)
|
||||
view.setUint32(24, sampleRate, true)
|
||||
view.setUint32(28, sampleRate * channels * 2, true)
|
||||
view.setUint16(32, channels * 2, true)
|
||||
view.setUint16(34, 16, true)
|
||||
writeString(view, 36, 'data')
|
||||
view.setUint32(40, dataLength, true)
|
||||
|
||||
new Int16Array(buffer, 44).set(samples)
|
||||
|
||||
return new Blob([buffer], { type: 'audio/wav' })
|
||||
}
|
||||
|
||||
function writeString(view: DataView, offset: number, string: string): void {
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
view.setUint8(offset + i, string.charCodeAt(i))
|
||||
if (sampleCount === 0) return false
|
||||
const rms = Math.sqrt(sumSquares / sampleCount)
|
||||
return rms >= SPEECH_RMS_THRESHOLD || peak >= SPEECH_PEAK_THRESHOLD
|
||||
} catch {
|
||||
return true
|
||||
} finally {
|
||||
await context?.close().catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioRecorder {
|
||||
private audioContext: AudioContext | null = null
|
||||
private mediaStream: MediaStream | null = null
|
||||
private source: MediaStreamAudioSourceNode | null = null
|
||||
private processor: ScriptProcessorNode | null = null
|
||||
private workletNode: AudioWorkletNode | null = null
|
||||
private chunks: Int16Array[] = []
|
||||
private totalSamples: number = 0
|
||||
private state: AudioRecorderState = 'idle'
|
||||
private options: AudioRecorderOptions
|
||||
private isAborted: boolean = false
|
||||
private mediaStream: MediaStream | null = null
|
||||
private mediaRecorder: MediaRecorder | null = null
|
||||
private chunks: Blob[] = []
|
||||
private firstChunkType = ''
|
||||
private isAborted = false
|
||||
private outputType = ''
|
||||
|
||||
private onStateChange?: (state: AudioRecorderState) => void
|
||||
private onError?: (error: string) => void
|
||||
private onDataAvailable?: (blob: Blob) => void
|
||||
|
||||
constructor(options: AudioRecorderOptions = {}) {
|
||||
this.options = { ...DEFAULT_OPTIONS, ...options }
|
||||
}
|
||||
private onNoSpeech?: () => void
|
||||
|
||||
static isSupported(): boolean {
|
||||
return !!(
|
||||
@@ -106,7 +78,7 @@ export class AudioRecorder {
|
||||
navigator.mediaDevices &&
|
||||
typeof navigator.mediaDevices.getUserMedia === 'function' &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.AudioContext !== 'undefined'
|
||||
typeof window.MediaRecorder !== 'undefined'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -126,6 +98,10 @@ export class AudioRecorder {
|
||||
this.onDataAvailable = callback
|
||||
}
|
||||
|
||||
setOnNoSpeech(callback: () => void): void {
|
||||
this.onNoSpeech = callback
|
||||
}
|
||||
|
||||
private setState(newState: AudioRecorderState): void {
|
||||
this.state = newState
|
||||
this.onStateChange?.(newState)
|
||||
@@ -141,56 +117,45 @@ export class AudioRecorder {
|
||||
try {
|
||||
this.isAborted = false
|
||||
this.chunks = []
|
||||
this.totalSamples = 0
|
||||
this.firstChunkType = ''
|
||||
|
||||
this.mediaStream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
},
|
||||
})
|
||||
this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: DEFAULT_AUDIO_CONSTRAINTS })
|
||||
|
||||
this.audioContext = new AudioContext({
|
||||
sampleRate: this.options.sampleRate,
|
||||
})
|
||||
|
||||
this.source = this.audioContext.createMediaStreamSource(this.mediaStream)
|
||||
|
||||
if (this.audioContext.audioWorklet) {
|
||||
try {
|
||||
await ensureWorkletLoaded(this.audioContext)
|
||||
this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor', {
|
||||
processorOptions: { targetSampleRate: this.options.sampleRate },
|
||||
})
|
||||
this.workletNode.port.onmessage = (e: MessageEvent<Int16Array>) => {
|
||||
this.chunks.push(e.data)
|
||||
this.totalSamples += e.data.length
|
||||
}
|
||||
this.source.connect(this.workletNode)
|
||||
} catch (error) {
|
||||
this.audioContext.close()
|
||||
this.audioContext = null
|
||||
throw new Error('Failed to load audio worklet processor', { cause: error })
|
||||
}
|
||||
} else if (this.audioContext) {
|
||||
const bufferSize = 4096
|
||||
this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1)
|
||||
const targetRate = this.options.sampleRate ?? 16000
|
||||
const inputRate = this.audioContext.sampleRate
|
||||
this.processor.onaudioprocess = (e) => {
|
||||
const inputData = e.inputBuffer.getChannelData(0)
|
||||
const int16Chunk = downsampleAndConvert(inputData, inputRate, targetRate)
|
||||
this.chunks.push(int16Chunk)
|
||||
this.totalSamples += int16Chunk.length
|
||||
}
|
||||
this.source.connect(this.processor)
|
||||
if (this.isAborted) {
|
||||
this.releaseResources()
|
||||
return
|
||||
}
|
||||
|
||||
const selectedMimeType = selectMimeType()
|
||||
this.mediaRecorder = new MediaRecorder(
|
||||
this.mediaStream,
|
||||
selectedMimeType ? { mimeType: selectedMimeType } : undefined,
|
||||
)
|
||||
|
||||
this.outputType = this.mediaRecorder.mimeType || selectedMimeType || ''
|
||||
|
||||
this.mediaRecorder.ondataavailable = (e: BlobEvent) => {
|
||||
if (e.data.size > 0) {
|
||||
if (this.chunks.length === 0 && e.data.type) {
|
||||
this.firstChunkType = e.data.type
|
||||
}
|
||||
this.chunks.push(e.data)
|
||||
}
|
||||
}
|
||||
|
||||
this.mediaRecorder.onstop = () => {
|
||||
this.finishRecording()
|
||||
}
|
||||
|
||||
this.mediaRecorder.onerror = () => {
|
||||
this.reset('error')
|
||||
this.onError?.('MediaRecorder error')
|
||||
}
|
||||
|
||||
this.mediaRecorder.start()
|
||||
this.setState('recording')
|
||||
} catch (error) {
|
||||
this.setState('error')
|
||||
this.cleanup()
|
||||
this.reset('error')
|
||||
|
||||
if (error instanceof DOMException) {
|
||||
if (error.name === 'NotAllowedError') {
|
||||
@@ -209,73 +174,84 @@ export class AudioRecorder {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.processor || this.workletNode) {
|
||||
this.processRecording()
|
||||
if (!this.mediaRecorder || this.mediaRecorder.state !== 'recording') {
|
||||
return
|
||||
}
|
||||
this.resetRecordingState()
|
||||
this.cleanup()
|
||||
this.setState('stopped')
|
||||
this.mediaRecorder.stop()
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.isAborted = true
|
||||
this.resetRecordingState()
|
||||
this.cleanup()
|
||||
this.setState('idle')
|
||||
}
|
||||
|
||||
private processRecording(): void {
|
||||
if (this.isAborted || this.chunks.length === 0 || this.totalSamples === 0) {
|
||||
private finishRecording(): void {
|
||||
if (this.isAborted) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const merged = new Int16Array(this.totalSamples)
|
||||
let offset = 0
|
||||
for (const chunk of this.chunks) {
|
||||
merged.set(chunk, offset)
|
||||
offset += chunk.length
|
||||
}
|
||||
const wavBlob = encodeWavFromInt16(merged, this.options.sampleRate ?? 16000, 1)
|
||||
this.onDataAvailable?.(wavBlob)
|
||||
} catch {
|
||||
this.onError?.('Failed to process recording')
|
||||
this.setState('error')
|
||||
const type = this.outputType || this.firstChunkType || ''
|
||||
const combinedBlob = new Blob(this.chunks, { type })
|
||||
|
||||
if (this.chunks.length === 0 || combinedBlob.size === 0) {
|
||||
this.onNoSpeech?.()
|
||||
this.reset('stopped')
|
||||
return
|
||||
}
|
||||
|
||||
const AudioContextClass = getAudioContextConstructor()
|
||||
if (!AudioContextClass) {
|
||||
this.onDataAvailable?.(combinedBlob)
|
||||
this.reset('stopped')
|
||||
return
|
||||
}
|
||||
|
||||
void this.finishRecordingWithSpeechDetection(combinedBlob, AudioContextClass)
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
if (this.workletNode) {
|
||||
this.workletNode.port.onmessage = null
|
||||
this.workletNode.port.postMessage('stop')
|
||||
this.workletNode.disconnect()
|
||||
this.workletNode = null
|
||||
private async finishRecordingWithSpeechDetection(combinedBlob: Blob, AudioContextClass: AudioContextConstructor): Promise<void> {
|
||||
const hasSpeech = await blobHasSpeech(combinedBlob, AudioContextClass)
|
||||
if (this.isAborted) {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.processor) {
|
||||
this.processor.onaudioprocess = null
|
||||
this.processor.disconnect()
|
||||
this.processor = null
|
||||
if (hasSpeech) {
|
||||
this.onDataAvailable?.(combinedBlob)
|
||||
} else {
|
||||
this.onNoSpeech?.()
|
||||
}
|
||||
|
||||
if (this.source) {
|
||||
this.source.disconnect()
|
||||
this.source = null
|
||||
}
|
||||
this.reset('stopped')
|
||||
}
|
||||
|
||||
if (this.audioContext && this.audioContext.state !== 'closed') {
|
||||
this.audioContext.close()
|
||||
this.audioContext = null
|
||||
}
|
||||
abort(): void {
|
||||
this.teardown()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.teardown()
|
||||
}
|
||||
|
||||
private teardown(): void {
|
||||
this.isAborted = true
|
||||
if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
|
||||
this.mediaRecorder.stop()
|
||||
}
|
||||
this.reset('idle')
|
||||
}
|
||||
|
||||
private stopTracks(): void {
|
||||
if (this.mediaStream) {
|
||||
this.mediaStream.getTracks().forEach(track => track.stop())
|
||||
this.mediaStream = null
|
||||
}
|
||||
}
|
||||
|
||||
private resetRecordingState(): void {
|
||||
private releaseResources(): void {
|
||||
this.stopTracks()
|
||||
this.mediaRecorder = null
|
||||
this.mediaStream = null
|
||||
this.chunks = []
|
||||
this.totalSamples = 0
|
||||
this.firstChunkType = ''
|
||||
this.outputType = ''
|
||||
}
|
||||
|
||||
private reset(nextState: AudioRecorderState): void {
|
||||
this.releaseResources()
|
||||
this.setState(nextState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { WebSpeechRecognizer } from './webSpeechRecognizer'
|
||||
|
||||
interface FakeSpeechRecognition {
|
||||
continuous: boolean
|
||||
interimResults: boolean
|
||||
lang: string
|
||||
maxAlternatives: number
|
||||
onstart: ((event: Event) => void) | null
|
||||
onend: ((event: Event) => void) | null
|
||||
onerror: ((event: { error: string }) => void) | null
|
||||
onresult: ((event: Record<string, unknown>) => void) | null
|
||||
start: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
abort: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function createFakeSpeechRecognition(): FakeSpeechRecognition {
|
||||
return {
|
||||
continuous: false,
|
||||
interimResults: false,
|
||||
lang: '',
|
||||
maxAlternatives: 1,
|
||||
onstart: null,
|
||||
onend: null,
|
||||
onerror: null,
|
||||
onresult: null,
|
||||
start: vi.fn(function (this: FakeSpeechRecognition) {
|
||||
setTimeout(() => {
|
||||
if (this.onstart) this.onstart(new Event('start'))
|
||||
}, 0)
|
||||
}),
|
||||
stop: vi.fn(),
|
||||
abort: vi.fn(),
|
||||
}
|
||||
}
|
||||
|
||||
function makeResultEvent(
|
||||
resultIndex: number,
|
||||
resultsLength: number,
|
||||
entries: Array<{
|
||||
isFinal: boolean
|
||||
transcript: string
|
||||
confidence: number
|
||||
}>,
|
||||
): Record<string, unknown> {
|
||||
const results: Record<number, Record<string, unknown>> = {}
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
results[i] = {
|
||||
isFinal: entries[i].isFinal,
|
||||
0: { transcript: entries[i].transcript, confidence: entries[i].confidence },
|
||||
}
|
||||
}
|
||||
return {
|
||||
resultIndex,
|
||||
results: { ...results, length: resultsLength },
|
||||
}
|
||||
}
|
||||
|
||||
describe('WebSpeechRecognizer', () => {
|
||||
let fakeRec: FakeSpeechRecognition
|
||||
|
||||
beforeEach(() => {
|
||||
fakeRec = createFakeSpeechRecognition()
|
||||
;(window as any).SpeechRecognition = vi.fn(() => fakeRec)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).SpeechRecognition
|
||||
})
|
||||
|
||||
it('configures continuous=true, interimResults=true, maxAlternatives=1, and lang on start()', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start({ language: 'en-US', interimResults: true, maxAlternatives: 1 })
|
||||
|
||||
expect(fakeRec.continuous).toBe(true)
|
||||
expect(fakeRec.interimResults).toBe(true)
|
||||
expect(fakeRec.maxAlternatives).toBe(1)
|
||||
expect(fakeRec.lang).toBe('en-US')
|
||||
})
|
||||
|
||||
it('appends multiple final result segments instead of replacing', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const results: Array<{ transcript: string; isFinal: boolean; confidence: number }> = []
|
||||
rec.onResult((r) => results.push(r))
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
]))
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(1, 2, [
|
||||
{ isFinal: false, transcript: 'hello', confidence: 0.9 },
|
||||
{ isFinal: true, transcript: 'world', confidence: 0.8 },
|
||||
]))
|
||||
|
||||
expect(rec.getFinalTranscript()).toBe('hello world')
|
||||
expect(results).toHaveLength(2)
|
||||
expect(results[0].transcript).toBe('hello')
|
||||
expect(results[1].transcript).toBe('world')
|
||||
})
|
||||
|
||||
it('emits combined final+interim transcript on interim events', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const interims: string[] = []
|
||||
rec.onInterimResult((t) => interims.push(t))
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
]))
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(1, 2, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
{ isFinal: false, transcript: 'world', confidence: 0.0 },
|
||||
]))
|
||||
|
||||
expect(interims).toHaveLength(1)
|
||||
expect(interims[0]).toBe('hello world')
|
||||
})
|
||||
|
||||
it('calls native stop after 2 seconds of inactivity following a result', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
|
||||
expect(fakeRec.stop).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('abort() clears accumulated transcript and inactivity timer', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
]))
|
||||
|
||||
expect(rec.getFinalTranscript()).toBe('hello')
|
||||
|
||||
rec.abort()
|
||||
expect(rec.getFinalTranscript()).toBe('')
|
||||
expect(fakeRec.abort).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.useFakeTimers()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('onend clears inactivity timer and sets state to idle', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('idle')
|
||||
|
||||
vi.useFakeTimers()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('removes one-shot start/error listeners after resolve so late errors do not leak', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onError = vi.fn()
|
||||
rec.onError(onError)
|
||||
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onerror!({ error: 'aborted' })
|
||||
|
||||
expect(onError).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('onend after error resets state to idle', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
expect(rec.getState()).toBe('error')
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('idle')
|
||||
expect(rec.isCurrentlyListening()).toBe(false)
|
||||
})
|
||||
|
||||
it('clearCallbacks clears pending inactivity timeout', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
rec.clearCallbacks()
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -65,6 +65,14 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
const WEB_SPEECH_INACTIVITY_TIMEOUT_MS = 2000;
|
||||
|
||||
export function appendTranscriptSegment(current: string, segment: string): string {
|
||||
const trimmedCurrent = current.trim();
|
||||
const trimmedSegment = segment.trim();
|
||||
return trimmedCurrent ? `${trimmedCurrent} ${trimmedSegment}` : trimmedSegment;
|
||||
}
|
||||
|
||||
export class WebSpeechRecognizer {
|
||||
private recognition: SpeechRecognition | null = null;
|
||||
private isListening = false;
|
||||
@@ -75,6 +83,25 @@ export class WebSpeechRecognizer {
|
||||
private onEndCallbacks: (() => void)[] = [];
|
||||
private onStartCallbacks: (() => void)[] = [];
|
||||
private finalTranscript = '';
|
||||
private inactivityTimeoutRef: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
private clearInactivityTimeout(): void {
|
||||
if (this.inactivityTimeoutRef !== null) {
|
||||
clearTimeout(this.inactivityTimeoutRef);
|
||||
this.inactivityTimeoutRef = null;
|
||||
}
|
||||
}
|
||||
|
||||
private resetInactivityTimeout(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.isListening) {
|
||||
this.inactivityTimeoutRef = setTimeout(() => {
|
||||
if (this.isListening) {
|
||||
this.stop();
|
||||
}
|
||||
}, WEB_SPEECH_INACTIVITY_TIMEOUT_MS);
|
||||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
if (typeof window === 'undefined') return;
|
||||
@@ -83,7 +110,7 @@ export class WebSpeechRecognizer {
|
||||
|
||||
if (RecognitionClass) {
|
||||
this.recognition = new RecognitionClass();
|
||||
this.recognition.continuous = false;
|
||||
this.recognition.continuous = true;
|
||||
this.recognition.interimResults = true;
|
||||
this.recognition.maxAlternatives = 1;
|
||||
|
||||
@@ -100,13 +127,15 @@ export class WebSpeechRecognizer {
|
||||
const result = event.results[i];
|
||||
|
||||
if (result.isFinal) {
|
||||
const segment = result[0].transcript;
|
||||
this.finalTranscript = appendTranscriptSegment(this.finalTranscript, segment);
|
||||
|
||||
const finalResult: SpeechRecognitionResult = {
|
||||
transcript: result[0].transcript,
|
||||
transcript: segment,
|
||||
isFinal: true,
|
||||
confidence: result[0].confidence || 1.0,
|
||||
};
|
||||
|
||||
this.finalTranscript = result[0].transcript;
|
||||
this.onResultCallbacks.forEach((cb) => cb(finalResult));
|
||||
} else {
|
||||
interimTranscript += result[0].transcript;
|
||||
@@ -116,9 +145,12 @@ export class WebSpeechRecognizer {
|
||||
if (interimTranscript) {
|
||||
this.onInterimResultCallbacks.forEach((cb) => cb(this.finalTranscript + ' ' + interimTranscript));
|
||||
}
|
||||
|
||||
this.resetInactivityTimeout();
|
||||
};
|
||||
|
||||
this.recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
|
||||
this.clearInactivityTimeout();
|
||||
this.state = 'error';
|
||||
this.isListening = false;
|
||||
|
||||
@@ -146,10 +178,9 @@ export class WebSpeechRecognizer {
|
||||
};
|
||||
|
||||
this.recognition.onend = () => {
|
||||
this.clearInactivityTimeout();
|
||||
this.isListening = false;
|
||||
if (this.state !== 'error') {
|
||||
this.state = 'idle';
|
||||
}
|
||||
this.state = 'idle';
|
||||
this.onEndCallbacks.forEach((cb) => cb());
|
||||
};
|
||||
}
|
||||
@@ -192,13 +223,23 @@ export class WebSpeechRecognizer {
|
||||
this.recognition.maxAlternatives = options.maxAlternatives;
|
||||
}
|
||||
|
||||
const onStartOnce = () => {
|
||||
let settled = false;
|
||||
|
||||
const cleanup = () => {
|
||||
settled = true;
|
||||
this.onStartCallbacks = this.onStartCallbacks.filter(cb => cb !== onStartOnce);
|
||||
this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce);
|
||||
};
|
||||
|
||||
const onStartOnce = () => {
|
||||
if (settled) return;
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
|
||||
const onErrorOnce = (error: string) => {
|
||||
this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce);
|
||||
if (settled) return;
|
||||
cleanup();
|
||||
reject(new Error(error));
|
||||
};
|
||||
|
||||
@@ -217,6 +258,7 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.stop();
|
||||
@@ -228,6 +270,7 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.abort();
|
||||
@@ -270,6 +313,7 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
clearCallbacks(): void {
|
||||
this.clearInactivityTimeout();
|
||||
this.onResultCallbacks = [];
|
||||
this.onInterimResultCallbacks = [];
|
||||
this.onErrorCallbacks = [];
|
||||
|
||||
Reference in new issue
Block a user