-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmic_test.js
317 lines (306 loc) · 12.3 KB
/
mic_test.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
function MicTest(audioContext, callbackExito, callbackError) {
this.audioContext = audioContext;
this.error = false;
this.inputChannelCount = 6;
this.outputChannelCount = 2;
this.callbackExito = callbackExito;
this.callbackError = callbackError;
this.audio = null;
this.mediaRecorder = null;
this.timeoutRecordId = null;
// Buffer size set to 0 to let Chrome choose based on the platform.
this.bufferSize = 0;
// Turning off echoCancellation constraint enables stereo input.
this.constraints = {
audio: {
/*optional: [
{echoCancellation: false}
]*/
}
};
this.collectSeconds = 2.0;
// At least one LSB 16-bit data (compare is on absolute value).
this.silentThreshold = 1.0 / 32767;
this.lowVolumeThreshold = -60;
// Data must be identical within one LSB 16-bit to be identified as mono.
this.monoDetectThreshold = 1.0 / 65536;
// Number of consequtive clipThreshold level samples that indicate clipping.
this.clipCountThreshold = 6;
this.clipThreshold = 1.0;
// Populated with audio as a 3-dimensional array:
// collectedAudio[channels][buffers][samples]
this.collectedAudio = [];
this.collectedSampleCount = 0;
for (var i = 0; i < this.inputChannelCount; ++i) {
this.collectedAudio[i] = [];
}
}
MicTest.prototype = {
/*
callbackStopMaxTime: Es un callback que se va a ejecutar después que pase
el tiempo máximo de grabación.
maxTimeForRecordMS: Es el tiempo máximo de grabación, por default es 15000 ms.
*/
record: function (callbackStopMaxTime, maxTimeForRecordMS) {
if (typeof this.audioContext === 'undefined') {
this.error = true;
console.log('WebAudio is not supported, test cannot run.');
} else {
var object = this;
navigator.mediaDevices.getUserMedia(object.constraints)
.then(function (stream) {
object.mediaRecorder = new MediaRecorder(stream);
object.mediaRecorder.start();
var audioChunks = [];
object.mediaRecorder.addEventListener("dataavailable", function (event) {
audioChunks.push(event.data);
});
object.mediaRecorder.addEventListener("stop", function () {
var audioBlob = new Blob(audioChunks, {type: "audio/mp4"});
var audioUrl = URL.createObjectURL(audioBlob)
object.audio = new Audio(audioUrl);
console.log(object.audio);
if (callbackStopMaxTime != null) {
callbackStopMaxTime();
}
});
if (maxTimeForRecordMS === null || isNaN(maxTimeForRecordMS)) {
maxTimeForRecordMS = 15000;
}
object.timeoutRecordId = setTimeout(function () {
object.stopRecording();
}, maxTimeForRecordMS);
})
.catch(function (error) {
if (object.callbackError !== undefined && object.callbackError !== null) {
object.callbackError();
}
});
}
},
stopRecording: function () {
if (this.timeoutRecordId != null) {
clearInterval(this.timeoutRecordId);
}
if (this.mediaRecorder != null && this.mediaRecorder.state === "recording") {
this.mediaRecorder.stop();
if (this.stream != null) {
var audioTracks = this.stream.getAudioTracks();
if (audioTracks != null && audioTracks.length > 0) {
if (audioTracks[0] != null) {
audioTracks[0].stop();
}
}
}
}
},
listenRecording: function (callbackFinishedAudio) {
var audio = this.audio;
console.log(audio);
audio.play();
audio.addEventListener("ended", function () {
if (callbackFinishedAudio !== undefined &&
callbackFinishedAudio !== null) {
callbackFinishedAudio();
}
});
/*this.audioContext.resume().then(function() {
});*/
},
stopListeningRecording: function () {
this.audio.pause();
},
run: function () {
if (typeof this.audioContext === 'undefined') {
this.error = true;
console.log('WebAudio is not supported, test cannot run.');
} else {
var object = this;
navigator.mediaDevices.getUserMedia(object.constraints)
.then(function (stream) {
//object.gotStream(stream);
if (object.callbackExito !== undefined && object.callbackExito !== null) {
object.callbackExito();
}
})
.catch(function (error) {
if (object.callbackError !== undefined && object.callbackError !== null) {
object.callbackError(error);
}
});
}
},
gotStream: function (stream) {
if (!this.checkAudioTracks(stream)) {
return;
}
this.createAudioBuffer(stream);
},
checkAudioTracks: function (stream) {
this.stream = stream;
var audioTracks = stream.getAudioTracks();
if (audioTracks.length < 1) {
this.error = true;
console.log('No audio track in returned stream.');
return false;
}
console.log('Audio track created using device=' + audioTracks[0].label);
return true;
},
createAudioBuffer: function () {
this.audioSource = this.audioContext.createMediaStreamSource(this.stream);
this.scriptNode = this.audioContext.createScriptProcessor(this.bufferSize,
this.inputChannelCount, this.outputChannelCount);
this.audioSource.connect(this.scriptNode);
this.scriptNode.connect(this.audioContext.destination);
this.scriptNode.onaudioprocess = this.collectAudio.bind(this);
this.stopCollectingAudio = setTimeoutWithProgressBar(
this.onStopCollectingAudio.bind(this), 5000);
},
collectAudio: function (event) {
// Simple silence detection: check first and last sample of each channel in
// the buffer. If both are below a threshold, the buffer is considered
// silent.
var sampleCount = event.inputBuffer.length;
var allSilent = true;
for (var c = 0; c < event.inputBuffer.numberOfChannels; c++) {
var data = event.inputBuffer.getChannelData(c);
var first = Math.abs(data[0]);
var last = Math.abs(data[sampleCount - 1]);
var newBuffer;
if (first > this.silentThreshold || last > this.silentThreshold) {
// Non-silent buffers are copied for analysis. Note that the silent
// detection will likely cause the stored stream to contain discontinu-
// ities, but that is ok for our needs here (just looking at levels).
newBuffer = new Float32Array(sampleCount);
newBuffer.set(data);
allSilent = false;
} else {
// Silent buffers are not copied, but we store empty buffers so that the
// analysis doesn't have to care.
newBuffer = new Float32Array();
}
this.collectedAudio[c].push(newBuffer);
}
if (!allSilent) {
this.collectedSampleCount += sampleCount;
if ((this.collectedSampleCount / event.inputBuffer.sampleRate) >=
this.collectSeconds) {
this.stopCollectingAudio();
}
}
},
onStopCollectingAudio: function () {
this.stream.getAudioTracks()[0].stop();
this.audioSource.disconnect(this.scriptNode);
this.scriptNode.disconnect(this.audioContext.destination);
this.analyzeAudio(this.collectedAudio);
if (this.error) {
console.log("Error");
this.callbackError();
} else {
console.log("Éxito");
this.callbackExito();
}
},
analyzeAudio: function (channels) {
var activeChannels = [];
for (var c = 0; c < channels.length; c++) {
if (this.channelStats(c, channels[c])) {
activeChannels.push(c);
}
}
if (activeChannels.length === 0) {
this.error = true;
console.log('No active input channels detected. Microphone ' +
'is most likely muted or broken, please check if muted in the ' +
'sound settings or physically on the device. Then rerun the test.');
} else {
console.log('Active audio input channels: ' + activeChannels.length);
}
if (activeChannels.length === 2) {
this.detectMono(channels[activeChannels[0]], channels[activeChannels[1]]);
}
},
channelStats: function (channelNumber, buffers) {
var maxPeak = 0.0;
var maxRms = 0.0;
var clipCount = 0;
var maxClipCount = 0;
for (var j = 0; j < buffers.length; j++) {
var samples = buffers[j];
if (samples.length > 0) {
var s = 0;
var rms = 0.0;
for (var i = 0; i < samples.length; i++) {
s = Math.abs(samples[i]);
maxPeak = Math.max(maxPeak, s);
rms += s * s;
if (maxPeak >= this.clipThreshold) {
clipCount++;
maxClipCount = Math.max(maxClipCount, clipCount);
} else {
clipCount = 0;
}
}
// RMS is calculated over each buffer, meaning the integration time will
// be different depending on sample rate and buffer size. In practise
// this should be a small problem.
rms = Math.sqrt(rms / samples.length);
maxRms = Math.max(maxRms, rms);
}
}
if (maxPeak > this.silentThreshold) {
var dBPeak = this.dBFS(maxPeak);
var dBRms = this.dBFS(maxRms);
console.log('Channel ' + channelNumber + ' levels: ' +
dBPeak.toFixed(1) + ' dB (peak), ' + dBRms.toFixed(1) + ' dB (RMS)');
if (dBRms < this.lowVolumeThreshold) {
this.error = true;
console.log('Microphone input level is low, increase input ' +
'volume or move closer to the microphone.');
}
if (maxClipCount > this.clipCountThreshold) {
console.log('Clipping detected! Microphone input level ' +
'is high. Decrease input volume or move away from the microphone.');
}
return true;
}
return false;
},
detectMono: function (buffersL, buffersR) {
var diffSamples = 0;
for (var j = 0; j < buffersL.length; j++) {
var l = buffersL[j];
var r = buffersR[j];
if (l.length === r.length) {
var d = 0.0;
for (var i = 0; i < l.length; i++) {
d = Math.abs(l[i] - r[i]);
if (d > this.monoDetectThreshold) {
diffSamples++;
}
}
} else {
diffSamples++;
}
}
if (diffSamples > 0) {
console.log('Stereo microphone detected.');
} else {
console.log('Mono microphone detected.');
}
},
dBFS: function (gain) {
var dB = 20 * Math.log(gain) / Math.log(10);
// Use Math.round to display up to one decimal place.
return Math.round(dB * 10) / 10;
},
};