-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathweb_voice_processor.js
43 lines (36 loc) · 1.62 KB
/
web_voice_processor.js
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
40
41
42
43
WebVoiceProcessor = (function () {
let downsampler;
let isRecording = false;
let start = function (engines, downsamplerScript, errorCallback) {
if (!downsampler) {
navigator.mediaDevices.getUserMedia({audio: true})
.then(stream => {
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let audioSource = audioContext.createMediaStreamSource(stream);
let node = audioContext.createScriptProcessor(4096, 1, 1);
node.onaudioprocess = function (e) {
if (!isRecording) {
return;
}
downsampler.postMessage({command: "process", inputFrame: e.inputBuffer.getChannelData(0)});
};
audioSource.connect(node);
node.connect(audioContext.destination);
downsampler = new Worker(downsamplerScript);
downsampler.postMessage({command: "init", inputSampleRate: audioSource.context.sampleRate});
downsampler.onmessage = function (e) {
engines.forEach(function (engine) {
engine.postMessage({command: "process", inputFrame: e.data});
});
};
})
.catch(errorCallback);
}
isRecording = true;
};
let stop = function () {
isRecording = false;
downsampler.postMessage({command: "reset"});
};
return {start: start, stop: stop};
})();