-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmicrophone.js
82 lines (71 loc) · 2.13 KB
/
microphone.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { EventEmitter } from 'events';
// import PCMConvert from 'pcm-convert';
export default class Microphone extends EventEmitter {
constructor(sampleRate = 16000) {
super();
this.rawStream = null;
this.stream = null;
this.audioProcessor = null;
this.audioContext = new AudioContext();
this.bufferSize = 4096;
this.sampleRate = sampleRate;
this.open();
}
/**
* Opens & initializes the Microphone stream from the browser
*/
open() {
navigator.mediaDevices.getUserMedia({
audio: true,
video: false,
}).then((rawStream) => {
this.rawStream = rawStream;
this.stream = this.audioContext.createMediaStreamSource(this.rawStream);
this.audioProcessor = this.audioContext.createScriptProcessor(this.bufferSize, 1, 1);
this.audioProcessor.onaudioprocess = event => this.onAudioProcess(event);
this.stream.connect(this.audioProcessor);
this.audioProcessor.connect(this.audioContext.destination);
this.emit('ready');
});
}
/**
* Processes the audio to be ready for Google.
*
* @param event event
*/
onAudioProcess(event) {
if (!this.enabled) return;
let data = event.inputBuffer.getChannelData(0);
data = this.downsampleBuffer(data);
// [TODO]: Implement piping?
this.emit('data', data);
}
/**
* Downsamles the buffer if needed to right sampleRate & converts the data into an int16 buffer
*
* @param buffer buffer
*/
downsampleBuffer(buffer) {
if (this.audioContext.sampleRate === this.sampleRate) {
return buffer;
}
const sampleRateRatio = this.audioContext.sampleRate / this.sampleRate;
const newLength = Math.round(buffer.length / sampleRateRatio);
const result = new Int16Array(newLength);
let offsetResult = 0;
let offsetBuffer = 0;
while (offsetResult < result.length) {
const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
let accum = 0;
let count = 0;
for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i += 1) {
accum += buffer[i];
count += 1;
}
result[offsetResult] = Math.min(1, accum / count) * 0x7FFF;
offsetResult += 1;
offsetBuffer = nextOffsetBuffer;
}
return result.buffer;
}
}