-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
modules-demo.html
975 lines (927 loc) · 38.6 KB
/
modules-demo.html
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SEPIA Web Audio Processor Test</title>
<script src="src/visualization/uPlot.iife.min.js?v=1.5.2"></script>
<script src="src/visualization/uPlot-lazy.min.js?v=0.9.2"></script>
<script src="src/visualization/uPlot-lazy-heatmap.min.js?v=0.9.2"></script>
<link rel="stylesheet" href="src/visualization/uPlot.min.css?v=1.5.2">
<!--<script src="src/polyfills/audioworklet-polyfill.js"></script>-->
<script type="text/javascript" src="src/sepia-web-audio.js?v=0.9.10"></script>
<script>
//set correct modules folder
if (window.SepiaFW) SepiaFW.webAudio.defaultProcessorOptions.moduleFolder = "src/modules";
else alert("SEPIA Web Audio Library not found or not supported (IE11?)!");
</script>
<script type="text/javascript" src="src/resources/pcm-convert.js?v=0.9.7"></script>
<script type="text/javascript" src="src/resources/opus-file-splitter.js?v=0.9.7"></script>
<script type="text/javascript" src="src/resources/fir-filter-resampler.js?v=0.9.7"></script>
<link rel="stylesheet" type="text/css" href="test-pages/tests.css?v=0.9.7">
<style></style>
</head>
<body>
<div id="mainView">
<h1>SEPIA Web Audio Processor - Module Tests</h1>
<div id="info">Info: []</div>
<div id="status"></div>
<div>
<button onclick="createRecorder(this);">Create</button>
<button onclick="startRecording(this);">Start</button>
<button onclick="stopRecording(this);">Stop</button>
<button onclick="releaseRecorder(this);">Release</button>
</div>
<div id="inputSourceOptions" class="contorlGroup center">
<div><label>Target Sample-Rate:</label><select id="sampleRateSelector">
<option value="" selected>Auto</option>
<option value="8000">8000</option>
<option value="16000">16000</option>
<option value="44000">44100</option>
<option value="48000">48000</option>
<option value="96000">96000</option>
</select></div>
<div><label>Audio Source:</label><select id="sourceTypeSelector" onchange="inputSourceChanged(this);">
<option value="mic" selected>Microphone</option>
<option value="whiteNoise">White-Noise Generator</option>
<option value="file1">File Stream 1</option>
<option value="file2">File Stream 2</option>
<option value="legacySpMic">Legacy Script-Processor Mic</option>
</select></div>
<div id="micOptions" class="contorlGroup">
<!-- created dynamically in code to show only supported -->
</div>
</div>
<div class="contorlGroup">
<label><b>Modules:</b></label>
<div><label>Volume-proc.:</label><input type="checkbox" id="useVolumeProcessor" checked onchange="useVolumeProcessor(this.checked);"></div>
<div><label>Resampler:</label><input type="checkbox" id="useResampler" checked onchange="useResampler(this.checked);"></div>
<div><label>Wave-encoder:</label><input type="checkbox" id="useWaveEncoder" checked onchange="useWaveEncoder(this.checked);"></div>
<div><label>VAD:</label><select id="vadWorkerSelect" onchange="setVadWorker(this.value);">
<option value="">off</option><option value="webrtc-vad-worker">WebRTC</option><option value="sepia-vad-worker" selected>SEPIA + MFCC (Beta)</option>
</select></div>
<div><label>Wake-Word:</label><input type="checkbox" id="useWakeWordWorker" onchange="useWakeWordWorker(this.checked);"></div>
</div>
<div style="position: relative;">
<div onclick="document.getElementById('logMessages').textContent='- Log -'"
style="position:absolute; right:0; top:0; padding:0 3px; border-radius:0 0 0 3px; border:1px solid #000; background:#f1f1f1; cursor:pointer; font-size:12px;">x</div>
<div id="logMessages">- Log -</div>
</div>
<div id="volumeMeterControls" class="contorlGroup">
<label><b>Volume-Processor</b></label>
<div><label>Gain:</label><input id="volumeMeterGain" class="small" type="number" value="1.0" onchange="setVolumeGain(+this.value);"></div>
<div><label>FPS:</label><input id="volumeMeterFps" class="small" value="40" onchange="setVolumeProcFps(+this.value);"></div>
<div style="display: inline-flex; align-items: center;"><label>Meter:</label><div id="volumeMeterNodeOutput"><div></div></div></div>
</div>
<div id="resamplerControls" class="contorlGroup">
<label><b>Resampler (Speex WASM)</b></label>
<div><label>Sample-Rate:</label><input id="resamplerSampleRate" class="small" value="16000" onchange="setResamplerSampleRate(this);" placeholder="16000"></div>
<div><label>Buffer-Size:</label><input id="resamplerBufferSize" class="small" value="512" onchange="setResamplerBufferSize(this);" placeholder="512"></div>
<div><label>Quality:</label><input id="resampleQuality" class="small" value="3" onchange="setResampleQuality(this);" placeholder="0-10 (0: fastest, 10: best)"></div>
<div id="resamplerGainBox" class="slidecontainer" style="display: none;">
<label>Gain:</label><input id="resamplerGain" type="range" min="1" max="50" step="1" value="1" class="slider"><input type="number" id="resamplerGainShow" class="small">
</div>
</div>
<div id="basicBufferControls" class="contorlGroup" style="display:none;">
<label><b>Basic Buffer</b></label>
<div><label>Buffer-Size:</label><input id="basicBufferSize" class="small" value="512" onchange="setResamplerBufferSize(this);" placeholder="512"></div>
</div>
<div id="vadWorkerControls" class="contorlGroup">
<label><b>VAD</b></label>
<div><label>Buffer-Size:</label><input id="vadWorkerBufferSize" class="small" value="512" placeholder="960" onchange="setVadWorkerBufferSize(+this.value);"></div>
<div><label>Mode:</label><input id="vadWorkerVadMode" class="small" type="number" value="1" placeholder="1-3 (3: agressive)" onchange="setVadWorkerVadMode(+this.value);"></div>
<div><label>Threshold:</label><input id="vadWorkerVadThreshold" class="small" type="number" value="0" step="0.1" title="e.g. ~1.3 (mode 1) or ~4 (mode 2-3)" onchange="setVadWorkerVadThreshold(+this.value);"></div>
</div>
<div id="wakeWordWorkerControls" class="contorlGroup">
<label><b>Wake-Word</b></label>
<div><label>Buffer-Size:</label><input disabled placeholder="same as input atm."></div>
<div><label>Sensitivity:</label><input id="wakeWordSensitivity" class="small" type="number" value="0.7" max="1" min="0" step="0.1" placeholder="0=low, 1=high" onchange="setWakeWordSensitivity(+this.value);"></div>
<div><label>Porcupine Version:</label><select id="porcupineVersionSelect" onchange="setPorcupineVersion(+this.value);">
<option value="14" selected>v1.4</option>
<option value="19">v1.9</option>
<option value="21">v2.1 (en)</option>
</select></div>
<div style="display: inline-flex; align-items: center;"><label>Gate:</label><div id="wakeWordGateState"></div><label></label></div>
<div><label>Control:</label><button onclick="wakeWordSetGate('open');">Listen</button><button onclick="wakeWordSetGate('close');">Stop</button><label></label></div>
<div><label>Key (v2+):</label><input id="porcupineAccessKey" placeholder="access key required for v2+"></div>
</div>
<div id="waveEncoderControls" class="contorlGroup">
<label><b>Wave Encoder</b></label>
<div><label>Lookback (ms):</label><input id="waveEncoderLookback" class="small" value="0" onchange="setWaveEncoderLookback(this);"></div>
<div><label>Record Max. (ms):</label><input id="waveEncoderRecordMax" class="small" value="6000" onchange="setWaveEncoderRecordMax(this);"></div>
<div style="display: inline-flex; align-items: center;"><label>Gate:</label><div id="waveEncoderGateState"></div><label></label></div>
<div><label>Control:</label><button onclick="waveEncoderSetGate('open');">Capture</button><button onclick="waveEncoderSetGate('close');">Stop</button><label></label></div>
<div><label>Export:</label><button onclick="waveEncoderGetWave();">Get Wave-File</button><button onclick="waveEncoderGetBuffer();">Show Buffer</button></div>
</div>
<div id="mediaRecorderControls" class="contorlGroup" style="display:none;">
<label><b>Media Recorder</b></label>
<div><label>Codec/format:</label><select id="mediaRecorderCodec"><option value="" selected>Default</option></select></div>
<div><label>Realtime Decoding:</label><input id="mediaRecorderDecode" type="checkbox"></div>
<div><label>Record Max. (ms):</label><input id="mediaRecorderRecordMax" class="small" value="6000"></div>
<div><label>Control:</label><button onclick="startMediaRecorder();">Capture</button><button onclick="stopMediaRecorder();">Stop</button></div>
<div><label>Export:</label><button onclick="getRawDataFromMediaRecorder();">Show Decoded Data</button></div>
</div>
<div class="contorlGroup">
<label><b>Show plots:</b></label>
<div style="flex: 1 0 100%;"></div>
<!--<div><label>Plot 1:</label><input type="checkbox" id="usePlot1" onchange="usePlot(1, this);"></div>-->
<div><label>Volume RMS:</label><input type="checkbox" id="usePlot2" checked onchange="usePlot(2, this);"></div>
<div><label>VAD:</label><input type="checkbox" id="usePlot3" onchange="usePlot(3, this);"></div>
<div><label>VAD Energy:</label><input type="checkbox" id="usePlot4" checked onchange="usePlot(4, this);"></div>
<div><label>VAD Mfcc (only SEPIA):</label><input type="checkbox" id="useHeatmap1" checked onchange="useHeatmap(1, this);"></div>
</div>
<!--<div id="chart1" class="chart"></div>-->
<div id="chart2" class="chart"></div>
<div id="chart3" class="chart" style="display: none;"></div>
<div id="chart4" class="chart"></div>
<div id="heatmap1" class="chart"></div>
</div>
<script type='text/javascript' src="test-pages/test-commons.js"></script>
<script type='text/javascript'>
var infoElement = document.getElementById('info');
var statusElement = document.getElementById('status');
var targetSampleRateSelector = document.getElementById("sampleRateSelector");
targetSampleRateSelector.onchange = function(){
targetSampleRate = +targetSampleRateSelector.value;
setResamplerSampleRate(targetSampleRateSelector, true);
};
var sourceSelector = document.getElementById("sourceTypeSelector");
var logElement = document.getElementById('logMessages');
//callbacks:
function onProcessorReady(info){
statusElement.className = "ready";
showLogMessage("onReady", info);
if (info.sourceInfo.label) showLogMessage("onReady details: sourceInfo.label", info.sourceInfo.label);
if (info.sourceInfo.settings) showLogMessage("onReady details: sourceInfo.settings", info.sourceInfo.settings);
infoElement.textContent = "Info: "
+ "Input Sample-Rate=" + info.inputSampleRate
+ " - Source-Type=" + info.sourceInfo.type;
console.log("onReady", info);
if (doUseWakeWordWorker) showLogMessage("Available wake-words", window.porcupineWorker.settings.options.setup.keywords);
//for testing:
if (!doUseWaveEncoder && rec.source.mediaStream) createMediaRecorder(rec.source.mediaStream, info.sourceInfo);
else document.getElementById("mediaRecorderControls").style.display = "none";
}
function onProcessorInitError(err){
statusElement.className = "";
showLogMessage("ERROR - onInitError", err);
console.error("onInitError", err);
}
function onAudioStart(info){
statusElement.className = "listening";
showLogMessage("onaudiostart", info);
console.log("onaudiostart", info);
}
function onAudioEnd(info){
statusElement.className = "ready";
showLogMessage("onaudioend", info);
console.log("onaudioend", info);
}
function onProcessorRelease(info){
statusElement.className = "";
showLogMessage("onrelease", info);
console.log("onrelease", info);
}
function onProcessorError(err){
statusElement.className = "";
showLogMessage("ERROR - Processor - onerror", err);
console.error("onerror", err);
}
function onDebugLog(msg){
console.log("debugLog", msg);
}
//main:
var rec;
var targetSampleRate = +targetSampleRateSelector.value; //e.g. 16000
var isLegacyScriptProcessor;
var scriptProcessorBufferSize = 512;
async function createRecorder(btn){
//audio source
var useWhiteNoiseTest = false; //document.getElementById("useWhiteNoiseRecorder").checked;
var customSource = undefined;
var audioSource = sourceSelector.value;
if (audioSource == "whiteNoise"){
//customSourceNode: white-noise
useWhiteNoiseTest = true;
}else if (audioSource.indexOf("file") == 0){
//customSourceNode: file audio buffer
try {
customSource = await createFileSource(audioSource);
}catch (err){
onProcessorInitError(err);
return;
}
}else if (audioSource == "legacySpMic"){
//customSourceNode: legacy script processor (with mic source)
try {
customSource = await SepiaFW.webAudio.createLegacyMicrophoneScriptProcessor({
targetSampleRate: targetSampleRate,
bufferSize: scriptProcessorBufferSize
});
isLegacyScriptProcessor = true;
}catch (err){
onProcessorInitError(err);
return;
}
}else{
//default: mic
}
//create processor modules
var volumeProcessor = {
name: 'volume-processor',
settings: {
onmessage: setVolume1, //info: 'onmessage' has the parameters: 'data' and 'processNodes'
options: {
//use AudioWorklet options directly or common "setup" field for worklet and workers:
processorOptions: {
gain: volGain, //e.g 2.0
fps: volProcFps //e.g 25
}
}
}
};
window.volumeProcessor = volumeProcessor;
var volumeProcessorIndex;
var resampler = {
name: 'speex-resample-switch', //'buffer-switch',
settings: {
onmessage: testBuffer,
sendToModules: [], //e.g. [waveEncoderIndex] - index as given to processor - 0: source, 1: module 1, ...
options: {
processorOptions: {
targetSampleRate: resamplerSampleRate, //16000,
resampleQuality: resamplerQuality, //7,
bufferSize: resamplerBufferSize, //512,
calculateRmsVolume: true,
//gain: +resamplerGain.value, //we can use this here but we have 'volumeProcessor' already ^^
passThroughMode: 1 //0: none, 1: original (float32), 2: 16Bit PCM - NOTE: NOT resampled
}
}
}
};
var resamplerWorker = {
name: 'speex-resample-worker',
type: 'worker',
settings: {
onmessage: testBuffer,
sendToModules: [], //e.g. [waveEncoderIndex] - index as given to processor - 0: source, 1: module 1, ...
options: {
setup: {
inputSampleSize: scriptProcessorBufferSize, //output bufferSize of previous module
targetSampleRate: resamplerSampleRate, //16000,
resampleQuality: resamplerQuality, //7,
bufferSize: resamplerBufferSize, //512, //TODO: set correct value (or replace with ratio?)
calculateRmsVolume: true,
gain: +resamplerGain.value //for the worker we keep it (because vol. is probably disabled)
}
}
}
};
var bufferSwitch = {
name: 'buffer-switch',
settings: {
onmessage: testBuffer,
sendToModules: [], //e.g. [waveEncoderIndex] - index as given to processor - 0: source, 1: module 1, ...
options: {
processorOptions: {
bufferSize: resamplerBufferSize, //512,
passThroughMode: 1, //0: none, 1: original (float32)
//TODO: add options for FIR resampler and float32toInt16 convert
}
}
}
};
var resamplerIndex;
var resamplerWorkerIndex;
var bufferSwitchIndex;
var waveEncoder = {
name: 'wave-encoder',
type: 'worker',
handle: {}, //will be updated on init. with ref. to node.
settings: {
onmessage: waveEncoderMessage,
options: {
setup: {
inputSampleRate: (doUseResampler? resamplerSampleRate : 0), //output sampleRate of previous module, if undefined take targetSampleRate or inputSampleRate
inputSampleSize: resamplerBufferSize, //output bufferSize of previous module
lookbackBufferMs: waveEncoderLookback,
//recordBufferLimitKb: 600,
recordBufferLimitMs: waveEncoderRecordMax,
isFloat32: (doUseResampler? false : true)
}
}
}
};
window.waveEncoder = waveEncoder;
var waveEncoderIndex;
var vadWorker = {
name: vadWorkerName || 'sepia-vad-worker', //More traditional version: 'webrtc-vad-worker',
type: 'worker',
settings: {
onmessage: setVoiceActivity,
//sendToModules: (doUseWaveEncoder? [waveEncoderIndex] : []),
options: {
setup: {
inputSampleRate: (doUseResampler? resamplerSampleRate : 0), //output sampleRate of previous module, if undefined take targetSampleRate or inputSampleRate
inputSampleSize: resamplerBufferSize, //output bufferSize of previous module
bufferSize: vadWorkerBufferSize,
vadMode: vadWorkerVadMode,
vadThreshold: vadWorkerVadThreshold,
//voiceEnergyCap: 50,
//voiceEnergyDropRate: 2,
sequence: {
//voiceActivationTime: 250,
//voiceResetTime: 1500,
//silenceActivationTime: 250,
maxSequenceTime: 6000,
minSequenceTime: 600
}
}
}
}
};
window.vadWorker = vadWorker;
var vadWorkerIndex;
var porcupineWorker = {
name: 'porcupine-wake-word-worker',
type: 'worker',
preLoad: {
wasmFile: ('src/modules/picovoice/porcupine-' + (porcupineVersion > 19? (porcupineVersion + "_" + porcupineLanguage) : porcupineVersion) + '.wasm')
},
settings: {
onmessage: onWakeWordMessage,
//sendToModules: (doUseWaveEncoder? [waveEncoderIndex] : []),
options: {
setup: {
inputSampleRate: (doUseResampler? resamplerSampleRate : 0),
inputSampleSize: resamplerBufferSize, //output bufferSize of previous module
bufferSize: resamplerBufferSize, //TODO: this has no effect yet
version: porcupineVersion,
porcupineLanguage: "en",
porcupineAccessKey: document.getElementById("porcupineAccessKey").value,
keywords: (porcupineVersion == 14? ["Hey SEPIA"] : ["Computer", "Jarvis", "Picovoice"]),
sensitivities: (porcupineVersion == 14? [wakeWordSensitivity] : [wakeWordSensitivity, wakeWordSensitivity, wakeWordSensitivity]),
keywordsRemoteLocation: ""
//can be used in combination with keyword names like ["Server: My Word"] for path like: [keywordsRemoteLocation]/2.0_en/keywords/[my_word]_wasm_20_en.js
}
}
}
};
window.porcupineWorker = porcupineWorker;
var porcupineWorkerIndex;
//put together modules
var activeModules = [];
if (doUseVolumeProcessor){
activeModules.push(volumeProcessor);
volumeProcessorIndex = activeModules.length;
}
if (doUseResampler && !isLegacyScriptProcessor){
activeModules.push(resampler);
resamplerIndex = activeModules.length;
}else if (doUseResampler && isLegacyScriptProcessor){
activeModules.push(resamplerWorker);
resamplerWorkerIndex = activeModules.length;
}else if (!isLegacyScriptProcessor){
activeModules.push(bufferSwitch);
bufferSwitchIndex = activeModules.length;
}
if (doUseVadWorker){
activeModules.push(vadWorker);
vadWorkerIndex = activeModules.length;
//add to send function
bufferSwitch.settings.sendToModules.push(vadWorkerIndex);
resampler.settings.sendToModules.push(vadWorkerIndex);
resamplerWorker.settings.sendToModules.push(vadWorkerIndex);
}
if (doUseWakeWordWorker){
activeModules.push(porcupineWorker);
porcupineWorkerIndex = activeModules.length;
//add to send function
bufferSwitch.settings.sendToModules.push(porcupineWorkerIndex);
resampler.settings.sendToModules.push(porcupineWorkerIndex);
resamplerWorker.settings.sendToModules.push(porcupineWorkerIndex);
}
if (doUseWaveEncoder){
activeModules.push(waveEncoder);
waveEncoderIndex = activeModules.length;
//add to send function
bufferSwitch.settings.sendToModules.push(waveEncoderIndex);
resampler.settings.sendToModules.push(waveEncoderIndex);
resamplerWorker.settings.sendToModules.push(waveEncoderIndex);
}
//create processor
rec = new SepiaFW.webAudio.Processor({
onaudiostart: onAudioStart,
onaudioend: onAudioEnd,
onrelease: onProcessorRelease,
onerror: onProcessorError,
targetSampleRate: targetSampleRate,
//targetBufferSize: 512,
modules: activeModules,
destinationNode: undefined, //defaults to: new "blind" destination (mic) or audioContext.destination (stream)
startSuspended: true,
debugLog: onDebugLog,
customSourceTest: useWhiteNoiseTest,
customSource: customSource,
initializerTimeout: 8000
}, function(msg){
//Init. ready
onProcessorReady(msg);
}, function(err){
//Init. error
onProcessorInitError(err);
});
}
function startRecording(btn){
if (rec){
rec.start();
vibrate([42]);
}
}
function stopRecording(btn){
if (rec){
rec.stop();
//UI specific:
setVolumeBar({volume: 0.0});
vibrate([42,30,42]);
}
}
function releaseRecorder(btn){
if (rec){
rec.release();
}
}
//Input source options
var micAudioConstraintOptionElements = {
deviceId: '<div><label>deviceId (label):</label><select id="micDeviceId" onchange="setMicOption(\'deviceId\', this.value);"><option value="" selected>Default</option></select></div>',
//sampleRate: '<div><label>sampleRate:</label><input id="micSampleRate" style="width: 54px;" value="48000" onchange="setMicOption(\'sampleRate\', +this.value);"></div>',
channelCount: '<div><label>channelCount:</label><input id="micChannelCount" style="width: 24px;" value="1" onchange="setMicOption(\'channelCount\', +this.value);"></div>',
noiseSuppression: '<div><label>noiseSuppression:</label><input id="micNoiseSuppression" type="checkbox" checked onchange="setMicOption(\'noiseSuppression\', this.checked);"></div>',
autoGainControl: '<div><label>autoGainControl:</label><input id="micAutoGainControl" type="checkbox" onchange="setMicOption(\'autoGainControl\', this.checked);"></div>',
echoCancellation: '<div><label>echoCancellation:</label><input id="micEchoCancellation" type="checkbox" onchange="setMicOption(\'echoCancellation\', this.checked);"></div>'
};
(function(){
var micO = document.getElementById("micOptions");
micO.innerHTML = "";
var sac = SepiaFW.webAudio.getSupportedAudioConstraints();
Object.keys(sac).forEach(function(aco, i){
var oEle = micAudioConstraintOptionElements[aco];
if (oEle){
micO.innerHTML += oEle;
}else{
console.log("Skipped mic constraint option: " + aco);
}
});
var devSel = document.getElementById("micDeviceId");
devSel.innerHTML = '<option value="" selected>Default</option>';
SepiaFW.webAudio.getAudioDevices().then(function(devices){
window.audioInputDevicesFound = devices.input;
Object.keys(devices.input).forEach(function(label, i){
var deviceId = devices.input[label];
var opt = document.createElement("option");
opt.textContent = label;
opt.value = deviceId;
devSel.appendChild(opt);
});
}).catch(function(err){
console.error("Error in 'getAudioDevices'", err);
var opt = document.createElement("option");
opt.textContent = "ERROR";
opt.value = "";
devSel.appendChild(opt);
});
})();
function inputSourceChanged(ele){
if (!ele) ele = sourceSelector;
if (ele.value == "mic" || ele.value == "legacySpMic"){
document.getElementById("micOptions").style.display = "";
}else{
document.getElementById("micOptions").style.display = "none";
}
if (ele.value == "legacySpMic"){
document.getElementById("resamplerGainBox").style.display = "";
document.getElementById("useVolumeProcessor").checked = false;
useVolumeProcessor(false);
}else{
document.getElementById("resamplerGainBox").style.display = "none";
document.getElementById("useVolumeProcessor").checked = true;
useVolumeProcessor(true);
}
}
inputSourceChanged();
function setMicOption(optionName, value){
//This is the 'brute-force' method to set microphone constraints ... but they are not yet accessible via options
console.log("Set mic constraint option", optionName, value);
SepiaFW.webAudio.overwriteSupportedAudioConstraints[optionName] = value;
}
//Custom audio nodes
async function createFileSource(fileId){
var fileUrl;
if (fileId == "file2"){
fileUrl = "test-sounds/chatter_counting.ogg";
}else{
fileUrl = "test-sounds/traffic_counting.ogg";
}
showLogMessage("createFileSource", fileUrl);
var loop = true; //default is true
var onEndCallback = function(){
console.log("Audio file source stream ended."); //only triggers if loop=false
};
return SepiaFW.webAudio.createFileSource(fileUrl, {
targetSampleRate: targetSampleRate
}, loop, onEndCallback);
}
//Audio node data/visualizations:
function setVolume1(data){
//console.log(data);
//if (data.rms != undefined){}
if (data.avg != undefined){
setVolumeBar(data.avg);
}
if (data.isClipped){
setVolumeBarClipped();
}
}
function setVolume2(data){
//console.log(data.samples);
if (data.rms != undefined){
plotData(data.rms, 2);
}else{
console.log(data);
}
}
function testBuffer(data){
if (data.rms != undefined){
setVolume2(data);
}
if (data.test){
console.error("test", data.test);
window.newBuff = data.test;
if (data.sampleRate){
SepiaFW.webAudio.encodeWaveBuffer(window.newBuff, data.sampleRate, data.channels || 1, true, function(r){
addWaveToPage(r.wav);
plotData(data.test);
});
}
}
}
function onWakeWordMessage(msg){
//console.log(msg);
if (msg && msg.keyword){
showLogMessage("Wake-word detected", msg.keyword);
}
}
function setVoiceActivity(data){
//console.log("vad", data);
if (data.voiceLoudness != undefined){
data.voiceLoudness.forEach(function(ld){
plotData([[ld - data.movingAvgLoudness], 0, [data.maxLoudness - data.movingAvgLoudness]], 3, true); //[data.movingAvgLoudness]
});
}else if (data.voiceActivity != undefined){
plotData(data.voiceActivity, 3);
}
if (data.voiceEnergy != undefined){
plotData(data.voiceEnergy, 4);
}
if (data.vadSequenceCode != undefined){
console.log("VAD sequence event: " + data.vadSequenceMsg);
//1: voice start, 2: sequence started, 3: voice finished, 4: voice finished max. time, 5: full sequence complete
if (data.vadSequenceCode == 2 && doUseWaveEncoder && vadAutoActivate){
vadAutoActivate = false;
vadAutoActivateSequenceWasTrigger = false;
waveEncoderSetGate('open');
}
if (data.vadSequenceCode == 5 && waveEncoderGateOpen){
if ((data.vadSequenceEnded - data.vadSequenceStarted) > vadMinRecordTimeAfterActivate){
waveEncoderSetGate('close');
}else{
vadAutoActivateSequenceWasTrigger = true;
}
}
if (waveEncoderGateOpen && vadAutoActivateSequenceWasTrigger && (data.vadSequenceCode == 3 || data.vadSequenceCode == 4 )){
waveEncoderSetGate('close');
}
//trigger data result
if (data.vadSequenceCode == 6){
console.log("vadSequenceCode=6", data);
addTitleToPage("VAD result group");
if (data.loudnessProfile){
//plotData(data.loudnessProfile);
plotData([data.loudnessProfile, createArrayWithStartValue(data.loudnessProfile.length, vadWorkerVadThreshold)], undefined, true);
}
if (data.featuresArray){
plotData(data.featuresArray[0]);
plotData(data.featuresArray[1]);
//plotData(data.featuresArray[2]);
drawHeatmap(data.featuresArray[2], undefined, data.featuresArray[2].length);
}
if (data.mfccProfile){
drawHeatmap(data.mfccProfile, undefined, data.mfccProfile.length);
}
}
}
if (useHeatmaps[1] && data.mfcc != undefined){
drawHeatmap(data.mfcc, 1, 150);
}
}
var heatmap1;
var vadAutoActivate = true;
var vadAutoActivateSequenceWasTrigger = false;
var vadMinRecordTimeAfterActivate = 3000;
var doUseVolumeProcessor = document.getElementById("useVolumeProcessor").checked;
var volMeterOut = document.getElementById('volumeMeterNodeOutput');
var volMeterOutBar = volMeterOut.firstChild;
var volMeterClipTimer;
var volGain = +document.getElementById('volumeMeterGain').value;
var volProcFps = +document.getElementById('volumeMeterFps').value;
//var volSmooth = 0.8; //0=none, 1=max
function setVolumeGain(val){
volGain = val;
if (window.volumeProcessor && volumeProcessor.handle){
volumeProcessor.handle.sendToModule({gain: {set: val}});
}
}
function setVolumeProcFps(val){
volProcFps = val;
if (window.volumeProcessor && volumeProcessor.handle){
volumeProcessor.handle.sendToModule({fps: {set: val}});
}
}
function setVolumeBar(vol){
//console.log("volume-bar data", data);
var volPercent = Math.min(100, Math.round(vol * 100));
volMeterOutBar.style.width = (volPercent + "%");
}
function setVolumeBarClipped(){
volMeterOut.style.outline = "1px solid red";
clearTimeout(volMeterClipTimer);
setTimeout(function(){ volMeterOut.style.outline = ""; }, 3000);
}
function useVolumeProcessor(useIt){
doUseVolumeProcessor = useIt;
if (useIt){
document.getElementById("volumeMeterControls").style.display = "";
}else{
document.getElementById("volumeMeterControls").style.display = "none";
}
}
useVolumeProcessor(doUseVolumeProcessor);
var doUseResampler = document.getElementById("useResampler").checked;
var resamplerSampleRate = +document.getElementById("resamplerSampleRate").value; //e.g. 16000;
var resamplerBufferSize = +document.getElementById("resamplerBufferSize").value; //e.g. 512;
var resamplerQuality = +document.getElementById("resampleQuality").value; //e.g. 7;
var resamplerGain = document.getElementById("resamplerGain");
var resamplerGainShow = document.getElementById("resamplerGainShow");
resamplerGainShow.value = resamplerGain.value;
resamplerGain.oninput = function(){ resamplerGainShow.value = resamplerGain.value; };
resamplerGainShow.oninput = function(){ resamplerGain.value = resamplerGainShow.value; };
function setResamplerSampleRate(inputEle, updateUi){
console.log('setResamplerSampleRate', +inputEle.value, updateUi);
if (updateUi){
resamplerSampleRate = +inputEle.value || 16000;
document.getElementById("resamplerSampleRate").value = resamplerSampleRate;
}else{
resamplerSampleRate = +inputEle.value;
}
}
function setResamplerBufferSize(inputEle){
resamplerBufferSize = +inputEle.value;
//kind of clumsy way to use this variable and function for both settings
if (doUseResampler){
document.getElementById("basicBufferSize").value = resamplerBufferSize;
}else{
document.getElementById("resamplerBufferSize").value = resamplerBufferSize;
}
}
function setResampleQuality(inputEle){
resamplerQuality = +inputEle.value;
}
function useResampler(useIt){
doUseResampler = useIt;
if (useIt){
document.getElementById("resamplerControls").style.display = "";
document.getElementById("basicBufferControls").style.display = "none";
}else{
document.getElementById("resamplerControls").style.display = "none";
document.getElementById("basicBufferControls").style.display = "";
}
}
useResampler(doUseResampler);
var doUseWaveEncoder = document.getElementById("useWaveEncoder").checked;
var waveEncoderLookback = +document.getElementById("waveEncoderLookback").value; //e.g. 0;
var waveEncoderRecordMax = +document.getElementById("waveEncoderRecordMax").value; //e.g. 6000;
var waveEncoderGate = document.getElementById('waveEncoderGateState');
var waveEncoderGateOpen = false;
function waveEncoderSetGate(state){
window.waveEncoder.handle.sendToModule({gate: state});
//waveEncoderGate.textContent = state;
waveEncoderGate.className = state;
waveEncoderGateOpen = (state == "open");
if (waveEncoderGateOpen == false){
vadAutoActivate = true;
}
console.log("waveEncoderSetGate", state);
}
function waveEncoderGetWave(){
window.waveEncoder.handle.sendToModule({request: {get: "wave"}});
}
function waveEncoderGetBuffer(){
window.waveEncoder.handle.sendToModule({request: {get: "buffer"}});
}
function setWaveEncoderLookback(ele){
waveEncoderLookback = +ele.value;
}
function setWaveEncoderRecordMax(ele){
waveEncoderRecordMax = +ele.value;
}
function waveEncoderMessage(data){
console.error("wave-encoder", data);
if (data.output && data.output.wav){
addWaveToPage(data.output.wav);
if (data.output.wav.byteLength){
var byteLen = data.output.wav.byteLength;
var samplesLen = data.output.totalSamples;
var time = Math.round(samplesLen/data.output.sampleRate*1000);
showLogMessage("waveEncoder", "created wave file - byteLength: " + byteLen + ", samples: " + samplesLen + ", time calc.: " + time);
}else{
showLogMessage("waveEncoder", "created wave file");
}
}else if (data.output && data.output.buffer){
plotData(data.output.buffer);
showLogMessage("waveEncoder", "buffer output length: " + data.output.buffer.length);
}
if (data.gate){
waveEncoderGate.className = data.gate.isOpen? "open" : "close";
if (data.gate.isOpen === false){
//waveEncoderGetBuffer(); //TODO: this destroys the lookback buffer
waveEncoderGetWave();
if (data.gate.closedAt){
showLogMessage("waveEncoder", "gate closed - time open (ms): " + (data.gate.closedAt - data.gate.openedAt));
}else{
showLogMessage("waveEncoder", "gate closed");
}
}
}
}
function useWaveEncoder(useIt){
doUseWaveEncoder = useIt;
if (useIt){
document.getElementById("waveEncoderControls").style.display = "";
document.getElementById("mediaRecorderControls").style.display = "none";
}else{
document.getElementById("waveEncoderControls").style.display = "none";
document.getElementById("mediaRecorderControls").style.display = "";
showMediaRecorderCodecs();
}
}
useWaveEncoder(doUseWaveEncoder);
var vadWorkerName = document.getElementById("vadWorkerSelect").value;
var doUseVadWorker = !!vadWorkerName;
var vadWorkerBufferSize = +document.getElementById("vadWorkerBufferSize").value; //e.g. 512 (Meyda) or 960 (WebRTC);
var vadWorkerVadMode = +document.getElementById("vadWorkerVadMode").value; //e.g. 3;
var vadWorkerVadThreshold = +document.getElementById("vadWorkerVadThreshold").value; //e.g. 4 (Meyda only, mode 1: 1.3, mode 2-n: 3-4;
function setVadWorkerBufferSize(val){
vadWorkerBufferSize = val;
}
function setVadWorkerVadMode(val){
vadWorkerVadMode = val;
}
function setVadWorkerVadThreshold(val){
vadWorkerVadThreshold = val;
}
function useVadWorker(useIt){
doUseVadWorker = useIt;
if (useIt){
document.getElementById("vadWorkerControls").style.display = "";
}else{
document.getElementById("vadWorkerControls").style.display = "none";
}
}
function setVadWorker(nuVadWorkerName){
useVadWorker(!!nuVadWorkerName);
vadWorkerName = nuVadWorkerName;
}
setVadWorker(vadWorkerName);
var doUseWakeWordWorker = document.getElementById("useWakeWordWorker").checked;
var wakeWordGate = document.getElementById('wakeWordGateState');
var wakeWordGateOpen = false;
var wakeWordSensitivity = +document.getElementById("wakeWordSensitivity").value;
var porcupineVersion = +document.getElementById("porcupineVersionSelect").value;
var porcupineLanguage = "en"; //TODO: add more
function setWakeWordSensitivity(sense){
wakeWordSensitivity = sense;
console.log("wakeWordSensitivity", wakeWordSensitivity);
}
function setPorcupineVersion(version){
porcupineVersion = version;
console.log("porcupineVersion", porcupineVersion);
}
function wakeWordSetGate(state){
window.porcupineWorker.handle.sendToModule({gate: state});
//wakeWordGate.textContent = state;
wakeWordGate.className = state;
wakeWordGateOpen = (state == "open");
console.log("wakeWordSetGate", state);
}
function useWakeWordWorker(useIt){
doUseWakeWordWorker = useIt;
if (useIt){
document.getElementById("wakeWordWorkerControls").style.display = "";
}else{
document.getElementById("wakeWordWorkerControls").style.display = "none";
}
}
useWakeWordWorker(doUseWakeWordWorker);
function showMediaRecorderCodecs(){
//add codec options
var codecSel = document.getElementById("mediaRecorderCodec");
codecSel.innerHTML = '<option value="" selected>Default</option>';
var selectedCodec = "";
var supportedCodecs = SepiaFW.webAudio.getSupportedMediaRecorderCodecs();
Object.keys(supportedCodecs).forEach(function(codec){
console.log("MediaRecorder codec:", codec, supportedCodecs[codec]);
var opt = document.createElement("option");
opt.textContent = codec;
opt.value = codec;
codecSel.appendChild(opt);
if (!selectedCodec) selectedCodec = codec;
});
codecSel.value = selectedCodec;
}
function createMediaRecorder(stream, sourceInfo){
//create
mediaRecorderChunks = [];
mediaRecorderSourceInfo = sourceInfo;
var mimeType;
var decodeToAudioBuffer = document.getElementById("mediaRecorderDecode").checked;
if (decodeToAudioBuffer){
showLogMessage("mediaRecorderWarning", "This recorder does not yet support decoding of chunks.");
}
var recordLimitMs = +document.getElementById("mediaRecorderRecordMax").value;
var codec = document.getElementById("mediaRecorderCodec").value;
console.log("AudioRecorder selected codec", codec);
var recorderOptions = {
codec: codec,
decodeToAudioBuffer: decodeToAudioBuffer,
recordLimitMs: recordLimitMs,
chunkSize: 2048,
onerror: function(err){ showLogMessage("mediaRecorderError", err); },
onstart: function(e){ showLogMessage("mediaRecorderStart", {}); },
onpause: function(e){ showLogMessage("mediaRecorderPause", {}); },
onresume: function(e){ showLogMessage("mediaRecorderResume", {}); },
onstop: function(e){
console.error("onstop"); //DEBUG
showLogMessage("mediaRecorderStop", {message: "Recorder stopped", chunkSize: mediaRecorderChunks.length});
if (decodeToAudioBuffer){
if (mediaRecorderChunks.length) plotData(...mediaRecorderChunks);
}else{
var blob = new Blob(mediaRecorderChunks, {'type' : mimeType});
addWaveToPage(blob);
}
},
ondataavailable: function(e){
if (e && e.data){
console.error("ondataavailable"); //DEBUG
mediaRecorderChunks.push(e.data);
//e.decodeTime
}
}
};
SepiaFW.webAudio.createAudioRecorder(stream, mediaRecorderSourceInfo, recorderOptions).then(function(res){
mimeType = res.mimeType;
showLogMessage("mediaRecorderCreated", "MIME-Type: " + res.mimeType + ", sample-time: " + res.sampleTime);
window.audioRecorder = res;
document.getElementById("mediaRecorderControls").style.display = "";
}).catch(function(err){
showLogMessage("mediaRecorderError", err);
document.getElementById("mediaRecorderControls").style.display = "none";
});
}
function startMediaRecorder(){
mediaRecorderChunks = [];
window.audioRecorder.start();
}
function stopMediaRecorder(){
window.audioRecorder.stop();
}
function getRawDataFromMediaRecorder(){
if (mediaRecorderChunks.length){
var start = Date.now();
//console.log("mediaRecorderSourceInfo", mediaRecorderSourceInfo);
function callback(audioBuffer){
console.log("decode time: " + (Date.now() - start));
var channelData = audioBuffer.getChannelData(0);
plotData(channelData);
console.log("decode+plot time: " + (Date.now() - start));
}
var sampleRate = mediaRecorderSourceInfo.settings.sampleRate;
var channels = mediaRecorderSourceInfo.settings.channelCount;
SepiaFW.webAudio.offlineAudioContextBlobDecoder(sampleRate, channels, new Blob(mediaRecorderChunks, {type: window.audioRecorder.mimeType}), callback);
}
}
var mediaRecorderChunks = [];
var mediaRecorderSourceInfo;
</script>
</body>
</html>