-
Notifications
You must be signed in to change notification settings - Fork 15
/
audioDetection.js
355 lines (279 loc) · 7.78 KB
/
audioDetection.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/* eslint-env browser */
/**
*
* @see
* https://stackoverflow.com/questions/9018771/how-to-best-determine-volume-of-a-signal
* https://dsp.stackexchange.com/questions/46147/how-to-get-the-volume-level-from-pcm-audio-data
*
*/
/**
* volumeState
*
* volume range state of a single sample. Possible values:
*
* 'mute'
* 'silence'
* 'signal'
* 'clipping' TODO
*
*/
let volumeState = 'mute'
let speechStarted = false
let silenceItems = 0
let signalItems = 0
let speechstartTime
let prerecordingItems = 0
let speechVolumesList = []
/**
* functions
*/
/*
* average
*
* calculate the average value of an array of numbers
*
*/
const average = (array) => array.reduce((a, b) => a + b) / array.length
const averageSignal = () => average(speechVolumesList).toFixed(4)
const maxSilenceItems = Math.round(MAX_INTERSPEECH_SILENCE_MSECS / SAMPLE_POLLING_MSECS)
const dispatchEvent = (eventName, eventData) => document.dispatchEvent(new CustomEvent( eventName, eventData ))
/**
* mute
*
* Emits 2 custom events:
*
* AUDIO SAMPLING:
* 'mute' -> audio volume is almost zero, the mic is off.
*
* MICROPHONE:
* 'mutedmic' -> microphone is MUTED (passing from ON to OFF)
*/
function mute(timestamp, duration) {
const eventData = {
detail: {
event: 'mute',
volume: meter.volume,
timestamp,
duration
}
}
dispatchEvent( 'mute', eventData )
// mic is muted (is closed)
// trigger event on transition
if (volumeState !== 'mute') {
dispatchEvent( 'mutedmic', eventData )
volumeState = 'mute'
}
}
/**
* signal
*
* Emits 3 custom events:
*
* AUDIO SAMPLING:
* 'signal' -> audio volume is high, so probably user is speaking.
*
* MICROPHONE:
* 'unmutedmic' -> microphone is UNMUTED (passing from OFF to ON)
*
* RECORDING:
* 'speechstart' -> speech START
*
*/
function signal(timestamp, duration) {
silenceItems = 0
const eventData = {
detail: {
event: 'signal',
volume: meter.volume,
timestamp,
duration,
items: ++ signalItems
}
}
if (! speechStarted) {
dispatchEvent( 'speechstart', eventData )
speechstartTime = timestamp
speechStarted = true
speechVolumesList = []
}
speechVolumesList.push(meter.volume)
dispatchEvent( 'signal', eventData )
// mic is unmuted (is open)
// trigger event on transition
if (volumeState === 'mute') {
dispatchEvent( 'unmutedmic', eventData )
volumeState = 'signal'
}
}
/**
* silence
*
* Emits 3 custom events:
*
* AUDIO SAMPLING:
* 'silence' -> audio volume is pretty low, the mic is on but there is not speech.
*
* MICROPHONE:
* 'unmutedmic' -> microphone is UNMUTED (passing from OFF to ON)
*
* RECORDING:
* 'speechstop' -> speech recording STOP (success, recording seems a valid speech)
* 'speechabort' -> speech recording ABORTED (because level is too low or audio duration length too short)
*
*/
function silence(timestamp, duration) {
signalItems = 0
const eventData = {
detail: {
event: 'silence',
volume: meter.volume,
timestamp,
duration,
items: ++ silenceItems
}
}
dispatchEvent( 'silence', eventData )
// mic is unmuted (goes ON)
// trigger event on transition
if (volumeState === 'mute') {
dispatchEvent( 'unmutedmic', eventData )
volumeState = 'silence'
}
//
// after a MAX_INTERSPEECH_SILENCE_MSECS
// a virdict event is generated:
// speechabort if audio chunck is to brief or at too low volume
// speechstop if audio chunk appears to be a valid speech
//
if ( speechStarted && (silenceItems === maxSilenceItems) ) {
const signalDuration = duration - MAX_INTERSPEECH_SILENCE_MSECS
const averageSignalValue = averageSignal()
// speech abort
// signal duration too short
if ( signalDuration < MIN_SIGNAL_DURATION ) {
eventData.detail.abort = `signal duration (${signalDuration}) < MIN_SIGNAL_DURATION (${MIN_SIGNAL_DURATION})`
dispatchEvent( 'speechabort', eventData )
}
// speech abort
// signal level too low
else if (averageSignalValue < MIN_AVERAGE_SIGNAL_VOLUME) {
eventData.detail.abort = `signal average volume (${averageSignalValue}) < MIN_AVERAGE_SIGNAL_VOLUME (${MIN_AVERAGE_SIGNAL_VOLUME})`
dispatchEvent( 'speechabort', eventData )
}
// speech stop
// audio chunk appears to be a valid speech
else {
dispatchEvent( 'speechstop', eventData )
}
speechStarted = false
}
}
/**
volume level
0.0 .---->-.----->--.-------->--.-------->--.------> 1.0
^ ^ ^ ^ ^
| | | | |
mute unmute silence speaking clipping
*/
function sampleThresholdsDecision(muteVolume, speakingMinVolume) {
const timestamp = Date.now()
const duration = timestamp - speechstartTime
//
// MUTE
// mic is OFF/mute (volume is ~0)
//
if (meter.volume < muteVolume )
mute(timestamp, duration)
//
// SIGNAL
// audio detection, maybe it's SPEECH
//
else if (meter.volume > speakingMinVolume )
signal(timestamp, duration)
//
// SILENCE
// mic is ON. Audio level is low (background noise)
//
else //(meter.volume < config.silenceVolume )
silence(timestamp, duration)
}
/**
* prerecording
*
* Emits the event:
*
* RECORDING:
* 'prespeechstart' -> speech prerecording START
*
* Every prespeechstartMsecs milliseconds,
* in SYNC with the main sampling (every timeoutMsecs milliseconds)
*
* @param {Number} prespeechstartMsecs
* @param {Number} timeoutMsecs
*
*/
function prerecording( prespeechstartMsecs, timeoutMsecs ) {
++ prerecordingItems
const eventData = {
detail: {
//event: 'prespeechstart',
volume: meter.volume,
timestamp: Date.now(),
items: prerecordingItems
}
}
// emit event 'prespeechstart' every prespeechstartMsecs.
// considering that prespeechstartMsecs is a multimple of timeoutMsecs
if ( (prerecordingItems * timeoutMsecs) >= prespeechstartMsecs) {
// emit the event if speech is not started
if ( !speechStarted )
dispatchEvent( 'prespeechstart', eventData )
prerecordingItems = 0
}
}
/**
* audio speech detection
*
* emit these DOM custom events:
*
* AUDIO SAMPLING:
* 'clipping' -> TODO, audio volume is clipping (~1),
* probably user is speaking, but volume produces distorsion
* 'signal' -> audio volume is high, so probably user is speaking.
* 'silence' -> audio volume is pretty low, the mic is on but there is not speech.
* 'mute' -> audio volume is almost zero, the mic is off.
*
* MICROPHONE:
* 'unmutedmic' -> microphone is UNMUTED (passing from OFF to ON)
* 'mutedmic' -> microphone is MUTED (passing from ON to OFF)
*
* RECORDING:
* 'prespeechstart' -> speech prerecording START
* 'speechstart' -> speech START
* 'speechstop' -> speech STOP (success, recording seems a valid speech)
* 'speechabort' -> speech ABORTED (because level is too low or audio duration length too short)
*
*
* @param {Object} config
* @see DEFAULT_PARAMETERS_CONFIGURATION object in audioDetectionConfig.js
*
* @see https://javascript.info/dispatch-events
*
*/
function audioDetection(config) {
setTimeout(
() => {
prerecording( config.prespeechstartMsecs, config.timeoutMsecs )
// to avoid feedback, recording could be suspended
// when the system play audio with a loudspeakers
if (config.recordingEnabled) {
sampleThresholdsDecision(config.muteVolume, config.speakingMinVolume)
}
// recursively call this function
audioDetection(config)
},
config.timeoutMsecs
)
}
//export { audioDetection }