Spaces:
Running
Running
Download static/worklets/mic.js from HuggingFaceM4/voice-agents-demo: direct link, hf CLI and curl.
- Browser
- Download file 1.4 kB
-
https://huggingface.co/spaces/HuggingFaceM4/voice-agents-demo/resolve/main/static/worklets/mic.js
- Command line
-
hf download hf://spaces/HuggingFaceM4/voice-agents-demo/static/worklets/mic.js
-
curl -L -o mic.js https://huggingface.co/spaces/HuggingFaceM4/voice-agents-demo/resolve/main/static/worklets/mic.js
1.4 kB
| // Captures the microphone, resamples to 24 kHz mono, and posts 40 ms PCM16 | |
| // frames plus a level reading to the main thread. | |
| const TARGET_RATE = 24000; | |
| const FRAME_SAMPLES = 960; | |
| class MicCapture extends AudioWorkletProcessor { | |
| constructor() { | |
| super(); | |
| this.step = sampleRate / TARGET_RATE; | |
| this.position = 0; | |
| this.previous = 0; | |
| this.frame = new Int16Array(FRAME_SAMPLES); | |
| this.filled = 0; | |
| this.peak = 0; | |
| } | |
| push(sample) { | |
| const clamped = Math.max(-1, Math.min(1, sample)); | |
| this.peak = Math.max(this.peak, Math.abs(clamped)); | |
| this.frame[this.filled++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff; | |
| if (this.filled === FRAME_SAMPLES) { | |
| const pcm = this.frame.buffer.slice(0); | |
| this.port.postMessage({ pcm, level: this.peak }, [pcm]); | |
| this.filled = 0; | |
| this.peak = 0; | |
| } | |
| } | |
| process(inputs) { | |
| const input = inputs[0] && inputs[0][0]; | |
| if (!input) return true; | |
| // Linear interpolation between the previous and current input sample. | |
| for (let i = 0; i < input.length; i++) { | |
| const current = input[i]; | |
| while (this.position < 1) { | |
| this.push(this.previous + (current - this.previous) * this.position); | |
| this.position += this.step; | |
| } | |
| this.position -= 1; | |
| this.previous = current; | |
| } | |
| return true; | |
| } | |
| } | |
| registerProcessor("mic-capture", MicCapture); | |