-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsupervisor.html
More file actions
1513 lines (1128 loc) · 57.6 KB
/
Copy pathsupervisor.html
File metadata and controls
1513 lines (1128 loc) · 57.6 KB
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Web based interpreter training tool">
<meta name="keywords" content="interpreter,interpreting,training,remote,web based,webrtc">
<!-- favicon for all devices -->
<link rel="apple-touch-icon" sizes="180x180" href="/images/icons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/images/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/images/icons/favicon-16x16.png">
<link rel="manifest" href="/images/icons/site.webmanifest">
<link rel="mask-icon" href="/images/icons/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="/images/icons/favicon.ico">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-config" content="/images/icons/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<title>intrain:supervisor</title>
<!--
Come registrare:
https://recordrtc.org/
https://github.com/muaz-khan/RecordRTC
https://github.com/streamproc/MediaStreamRecorder
// Solo registrazione audio da audiocontext
https://github.com/cwilso/AudioRecorder
https://webrtc.github.io/samples/src/content/getusermedia/record/
https://www.webrtc-experiment.com/RecordRTC/simple-demos/
https://webrtc.github.io/samples/src/content/peerconnection/pc1/
WebRTC server?
https://github.com/meetecho/janus-gateway
Explore HTML5 audio
https://dzone.com/articles/exploring-html5-web-audio
-->
<!-- script src="https://use.fontawesome.com/7f33ee3a55.js"></script -->
<script src="https://kit.fontawesome.com/ea65ac0a48.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="css/intrain.css?0.06">
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/jquery-migrate-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/jquery.swapelements.js"></script>
<script src="js/peerjs.min.js"></script>
<!-- script src="js/jquery.i18n.js"></script-->
<script src="js/utils.js?0.01"></script>
<script src="js/common.js?0.06"></script>
<script src="js/config.js?0.04"></script>
<script src="js/intrain.js?0.06"></script>
<script src="js/log.js?0.01"></script>
<script src="js/io-devices.js"></script>
<!-- https://github.com/daneden/animate.css -->
<link rel="stylesheet" href="css/animate.min.css">
<script src="js/animatecss.js"></script>
<!-- Decalage chronometer component -->
<link rel="stylesheet" href="css/decalage.css">
<script src="js/decalage.js"></script>
<!-- Audio recorder from AudioContext -->
<script src="js/recorderjs/recorder.js"></script>
<!-- Input clear button -->
<script src="js/bootstrap4-input-clearer.min.js"></script>
<!-- MediaElementJS HTML5 Video Player -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/mediaelementplayer.min.css">
<script src="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/mediaelement-and-player.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/renderers/dailymotion.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/renderers/facebook.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/renderers/soundcloud.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/renderers/twitch.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mediaelement@4.2.7/build/renderers/vimeo.min.js"></script>
<script>
speakerAudioMutedDefault = false;
interpreterAudioDefault = false;
// supervisorAudioMutedDefault = false;
speakerAudioMuted = speakerAudioMutedDefault;
interpreterAudioMuted = interpreterAudioDefault;
//supervisorAudioMuted = supervisorAudioMutedDefault;
myRole = RoleSupervisor;
myColor = ColorSupervisor;
// NB: speaker=1 (L), interpreter=2 (R)
var audioCtx = new AudioContext();
var split1 = audioCtx.createChannelSplitter(2); // Splitter di canali
var split2 = audioCtx.createChannelSplitter(2); // Splitter di canali
var gain1 = audioCtx.createGain(); // Volume canale 1
var gain2 = audioCtx.createGain(); // Volume canale 2
var mix = audioCtx.createChannelMerger(2, 2); // Mixer di canali
var channel1 = null;
var channel2 = null;
var speakerSource = null;
var interpreterSource = null;
var mySource = null;
// AudioRecorder: the two audio sources be mixed as separate L/R
// stereo tracks, both on mix (which will be eventually connected to
// the output) and mixrec, which is connected to the audio recorder
var zeroGain = null;
var mixrec = null; // Mixer di canali
var audioRecorder = null;
var recIndex = 1;
// Canvas to draw an audio waveform for the microphone
var micGraph = null;
var micGraphCanvasCtx = null;
function initRecorder() {
mixrec = audioCtx.createChannelMerger(2, 2); // Channel mixer for the recorder
audioRecorder = new Recorder( mixrec );
zeroGain = audioCtx.createGain();
split1.connect(mixrec, 0, 1);
split2.connect(mixrec, 0, 0);
// Connect to a gain node with gain value = 0 (so it will be
// silent) and then to destination to activate the audio flow
zeroGain.gain.value = 0.0;
mixrec.connect( zeroGain );
zeroGain.connect( audioCtx.destination );
}
// Various toggles
var swapChannels = false; // swap channels toggle variable
var boostVolume = false; // boost volume
var showPlayer = false; // show player and load controls
// Crossfade implementation
initCrossFader();
initRecorder();
// When the page has been loaded
$(document).ready(function() {
micGraph = $("#vumeter")[0];
micGraphCanvasCtx = micGraph.getContext("2d");
// Init tooltips
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
// clear button in inputs
$(function() {
$('.clearer').clearer();
});
initMuted(); // Mute/unmute partners (set defaults)
loadClock(); // Start clock
// check for notifications support
// you can omit the 'window' keyword
if (window.Notification) {
console.log("Requesting permission to notify incoming connections.");
window.Notification.requestPermission();
} else {
console.warn("Notifications are not supported for this Browser/OS version yet.");
}
var playDelay = false;
// init player
$('#myplayer').mediaelementplayer({
startVolume: 1,
stretching: 'responsive',
controls: true,
alwaysShowControls: true,
features: ["playpause", "progress", "current", "duration", "tracks", "volume", "fullscreen"],
success: function(mediaElement, originalNode, instance) {
myVideoPlayer = instance;
myVideoMediaElement = mediaElement;
/*
mediaElement.addEventListener('loadstart', function() { console.log('loadstart'); }, false);
mediaElement.addEventListener('durationchange', function() { console.log('durationchange'); }, false);
mediaElement.addEventListener('loadedmetadata', function() { console.log('loadedmetadata'); }, false);
mediaElement.addEventListener('loadeddata', function() { console.log('loadeddata'); }, false);
mediaElement.addEventListener('canplay', function() { console.log('canplay'); }, false);
mediaElement.addEventListener('canplaythrough', function() { console.log('canplaythrough'); }, false);
mediaElement.addEventListener('suspend', function() { console.log('suspend'); }, false);
mediaElement.addEventListener('abort', function() { console.log('abort'); }, false);
mediaElement.addEventListener('error', function() { console.log('error'); }, false);
mediaElement.addEventListener('emptied', function() { console.log('emptied'); }, false);
mediaElement.addEventListener('stalled', function() { console.log('stalled'); }, false);
mediaElement.addEventListener('playing', function() { console.log('playing'); }, false);
mediaElement.addEventListener('waiting', function() { console.log('waiting'); }, false);
mediaElement.addEventListener('seeking', function() { console.log('seeking'); }, false);
mediaElement.addEventListener('seeked', function() { console.log('seeked'); }, false);
//mediaElement.addEventListener('timeupdate', function() { console.log('timeupdate'); }, false);
mediaElement.addEventListener('ended', function() { console.log('ended'); }, false);
mediaElement.addEventListener('ratechange', function() { console.log('ratechange'); }, false);
mediaElement.addEventListener('volumechange', function() { console.log('volumechange' ); }, false);
*/
mediaElement.addEventListener('progress', function() {
console.log('progress', myVideoPlayer.currentTime);
}, false);
mediaElement.addEventListener('pause', function() {
console.log('pause', myVideoPlayer.currentTime);
if (interpreterData && interpreterData.open)
interpreterData.send({action: "pausevideo"});
}, false);
mediaElement.addEventListener('play', function() {
console.log("play from", myVideoPlayer.currentTime);
if (interpreterData && interpreterData.open)
interpreterData.send({action: "playvideo"});
}, false);
instance.prepare = function() {
if (interpreterData && interpreterData.open)
interpreterData.send({action: "seekvideo", time: 0.0, pause: true});
myVideoPlayer.setCurrentTime(0.0);
myVideoPlayer.pause();
};
// These hacks are to get events (play, seek) before they're
// actually handled on the supervisor side, and run them on
// to the interpreter side so that they can be handled almost
// in parallel, reducing the delay.
var pfx = '.' + this.classPrefix;
$(pfx + 'playpause-button, ' + pfx + 'overlay-play').on('click', function() {
if (! myVideoPlayer.paused) {
if (interpreterData && interpreterData.open)
interpreterData.send({action: "playvideo"});
}
console.log("CLICK playpause button ( paused:", myVideoPlayer.paused, ")");
});
/*
$(pfx + 'overlay-button').on('click', function(e) {
console.log("CLICK overlay button ( paused:", myVideoPlayer.paused, ")");
});
*/
$(pfx + 'time-slider').on('click', function() {
var w = myVideoPlayer.total.offsetWidth;
var p = $(pfx + 'time-slider ' + pfx + 'time-hovered').attr("pos");
var d = myVideoPlayer.getDuration();
var percentage = p/w;
var t = (percentage <= 0.02 ? 0 : percentage * d) + 0.25;
if (t > d) t = d;
if (interpreterData && interpreterData.open)
interpreterData.send({action: "seekvideo", time: t.toFixed(4)});
console.log("seek video to", t.toFixed(4));
});
}
});
$('#login-dialog').modal({keyboard: false, backdrop: 'static'});
$('#cancel-button').attr("disabled", true);
speakerVideo = $("#speakerVideo")[0];
interpreterVideo = $("#interpreterVideo")[0];
localVideo = $("#localVideo")[0];
// Connect user video panel with webcam and headset
/*
navigator.mediaDevices
.getUserMedia(SupervisorMediaStreamConstraints)
.then(gotLocalMediaStream)
.catch(handleLocalMediaStreamError);
*/
setDeviceSelectors({
vs: $('#select-video-source')[0], // select box for video source devices
as: $('#select-audio-source')[0], // select box for audio source devices
ao: $('#select-audio-output')[0], // select box for audio output devices
});
$('#select-video-source').on('change', setUserMediaConstraints);
$('#select-audio-source').on('change', setUserMediaConstraints);
//$('#select-audio-output').on('change', changeAudioDestination);
navigator.mediaDevices
.enumerateDevices()
.then(gotDevices)
.catch(handleLocalMediaStreamError);
setUserMediaConstraints();
/* Clicked "connect" */
$('#join-button').on("click", function(e){
console.log("Connect/disconnect button pressed");
e.preventDefault();
// Toggle connect/disconnect
if (peerConnected) {
console.log("Closing...");
$("#login-info").html("You're disconnected");
$('#login-dialog').modal('show');
$('#cancel-button').attr("disabled", true);
if (speakerData && speakerData.open) {
speakerData.send({action: "leaving", message: "bye"});
}
if (interpreterData && interpreterData.open) {
interpreterData.send({action: "leaving", message: "bye"});
}
setTimeout(function() {
//supervisorData.close();
myPeer.destroy()
}, WaitBeforeClose);
return true;
}
// Enable cancel button in login form
$('#cancel-button').attr("disabled", false);
// Get username
userName = $("#username").val().trim();
if (userName == "") {
logToPanel("User name is empty", "info");
return false;
}
userID = userName.toLowerCase().hash64(); // userName.replace('@', "_AT_").replace('.', "_DOT_");
console.log("Peer: trying to create peer using supplied userID");
myPeer = new Peer(userID, PeerJSConfig, SupervisorPeerOptions);
// Handle incoming call calls
myPeer.on('call', function(c) {
var role = c.options.metadata.role; // Who's connecting
if (! verifyMediaConnection(c, role)) {
var dt = getDateTime();
var m = dt.hms + " - Incoming call from another " + role + " rejected because we're busy.";
console.warn("Peer: reject call from", role);
logToPanel(m, "danger");
logToChat(m);
c.close();
return false;
}
console.log("Peer: call from", role);
if (role == "speaker" || role == "interpreter") {
if (role == "speaker") {
speakerMedia = c;
} else {
interpreterMedia = c;
}
c.answer(localStream);
c.on('stream', function(mediaStream) {
if (role == "speaker") {
speakerVideo.srcObject = mediaStream;
speakerMediaStream = mediaStream;
speakerVideo.onloadedmetadata = function(e) {
speakerVideo.play();
speakerVideo.muted = true;
}
} else {
interpreterVideo.srcObject = mediaStream;
interpreterMediaStream = mediaStream;
interpreterVideo.onloadedmetadata = function(e) {
interpreterVideo.play();
interpreterVideo.muted = true;
}
}
initCrossFader();
});
c.on('close', function() {
resetConnection(role);
logToPanel("<b>" + role + "</b> media connection closed", "danger");
logToChat("<b>" + role + "</b> media connection closed");
console.log(role + " media connection closed");
initCrossFader();
});
}
});
var peerConnecting = false;
// Handle incoming data
myPeer.on('connection', function(c) {
console.log("Incoming connection");
var role = c.options.metadata.role; // Who's connecting
console.log("Peer: data connection from", role);
if (setupDataConnection(c, role)) {
console.log("Connection handle has been set for", role);
// Push a notification if permission is granted and
// only if the browser window is not focused
if (Notification.permission === "granted" && !document.hasFocus()) {
var notification = new Notification(
'Incoming connection from ' + role,
{
"icon": '/images/icons/favicon-16x16.png'
}
);
// Show browser window and close notification on user click
notification.onclick = function(e) {
e.preventDefault();
window.focus();
notification.close();
}
}
while (peerConnecting) {
setTimeout(() => { console.log("Wait for data connection to complete"); }, 500);
}
peerConnecting = true;
console.log(
"call from:" + role + "; " +
"speaker status:" + (speakerData ? (speakerData.open?"open":"closed") : "none") + "; " +
"interpreter status:" + (interpreterData ? (interpreterData.open?"open":"closed") : "none")
);
// if intepreter is connecting and speaker is already connected
// tell the speaker to call the intepreter
if (role == RoleInterpreter && speakerData && speakerData.open) {
console.log("Asking the speaker to call the intepreter (" + c.peer + ")");
setTimeout(function() {
speakerData.send({action: 'dial', peerid: c.peer, role: role});
}, 0);
}
// if speaker is connecting and intepreter is already connected
// tell the intepreter to call the speaker
if (role == RoleSpeaker && interpreterData && interpreterData.open) {
console.log("Asking the interpreter to call the speaker (" + c.peer + ")");
setTimeout(function() {
interpreterData.send({action: 'dial', peerid: c.peer, role: role});
}, 0);
}
// Handle data connections
switch (role) {
case RoleInterpreter:
case RoleSpeaker:
c.on('data', function(data) {
var act = (typeof data === "object") ? data.action : "chat";
console.log("received:", data);
switch (act) {
case 'chat':
logToChat(data.message, role, role == RoleSpeaker ? ColorSpeaker : ColorInterpreter);
break;
case 'leaving':
resetConnection(role);
logToPanel("<b>" + role + "</b> has logged out", "danger");
logToChat("<b>" + role + "</b> has logged out");
console.log(role + " has logged out");
initCrossFader();
break;
case 'sendfile':
var link = getFileDownloadLinkFromData(data);
if (link !== null) {
console.log("Received file '" + data.filename + "' of type '" + data.filetype + "' from " + role);
logToChat("The " + role + " has sent you a file: " + link);
} else {
console.warn("Invalid file transfer from", role);
logToChat("Invalid file transfer from", role);
}
break;
}
});
peerConnecting = false;
break;
case RoleSupervisor:
break;
}
} else {
console.log("Rejecting connection");
//c.send({action: "reject", message: "This training session is busy"});
setTimeout(function() { c.close(); }, WaitBeforeClose);
//c.close()
return false;
}
});
myPeer.on('open', function(){
console.log("Peer: open");
// here you have myPeer.id
peerConnected = true;
peerError = false;
logToPanel("Connection successful. You're now logged on as <strong>" + userName + "</strong> [id=" + myPeer.id + "]. Your couterparts can now call you using the username you provided.", "success");
logToChat("New training session initiated");
$("#username").prop("disabled", true);
$("#join-button").text("Disconnect");
$("#join-button").removeClass("btn-primary").addClass("btn-warning");
$('#login-status').html('');
$('#login-dialog').modal('hide');
$("#login-info").html("You've joined the training session as <strong>" + userName + "</strong>. You are the <strong>" + myRole + "</strong>.");
loadAndPlay("sounds/whistle.mp3");
});
myPeer.on('close', function() {
peerConnected = false;
console.log("Peer: close");
logToPanel("Connection closed", "success");
logToChat("Training session closed");
$("#username").prop("disabled", false);
$("#join-button").text("Connect");
$("#join-button").removeClass("btn-warning").addClass("btn-primary");
});
myPeer.on('disconnected', function(){
// myPeer.reconnect();
});
myPeer.on('error', peerErrors);
return false;
});
loadCommonHandlers();
$('#swap-channels').on('click', function(){
swapChannels = !swapChannels;
$("label[for='swap-channels']").text(swapChannels ? "Swap R/L:" : "Swap L/R:" );
initCrossFader();
});
$('#boost-volume').on('click', function(){
boostVolume = !boostVolume;
$('#boost-volume > i').toggleClass("fa-volume-up fa-volume-down");
$('#cross-fader').trigger('input');
});
$('#cross-fader').on('input', function(){
var val = $(this).val();
var min = $(this).attr('min');
var max = $(this).attr('max');
var m1 = speakerAudioMuted ? 0.0001 : 1;
var m2 = interpreterAudioMuted ? 0.0001 : 1;
var b = parseInt(val) / (parseInt(max) - parseInt(min));
var v = boostVolume ? 8 : 2 ; //1.5*parseInt(volume.value) / (parseInt(volume.max) - parseInt(volume.min));
//console.log("Crossfade value:", b);
var vol1 = m1 * v * Math.cos((1.0 - b) * 0.5 * Math.PI);
var vol2 = m2 * v * Math.cos(b * 0.5 * Math.PI)
// exponentialRampToValueAtTime does not allow to set volume to 0
if (showPlayer && myVideoPlayer && !myVideoPlayer.paused) {
myVideoPlayer.setVolume(Math.cos((1.0 - b) * 0.5 * Math.PI));
gain1.gain.setValueAtTime(0, audioCtx.currentTime);
} else {
if (vol1 == 0) {
gain1.gain.setValueAtTime(0, audioCtx.currentTime);
} else {
gain1.gain.exponentialRampToValueAtTime(vol1, audioCtx.currentTime);
}
}
if (vol2 == 0) {
gain2.gain.setValueAtTime(0, audioCtx.currentTime);
} else {
gain2.gain.exponentialRampToValueAtTime(vol2, audioCtx.currentTime);
}
});
$('#run-player').on('click', function() {
var videoURL = $('#video-url').val();
myVideoPlayer.setSrc(videoURL);
if (interpreterData && interpreterData.open) {
console.log("Sending video " + videoURL + " to interpreter");
interpreterData.send({
action: "loadvideo",
url: videoURL,
time: /*myVideoPlayer.getCurrentTime() +*/ 0.01,
pause: true
});
//interpreterData.send({action: "seekvideo", time: 0.0, pause: true});
myVideoPlayer.setSrc(videoURL);
myVideoPlayer.setCurrentTime(0.0);
myVideoPlayer.pause();
}
//myVideoPlayer.play();
//myVideoPlayer.volume = 1;
console.log(videoURL);
});
$('#load-player').on('click', function() {
showPlayer = !showPlayer;
if (showPlayer) {
if (interpreterData && interpreterData.open)
interpreterData.send({action: "showplayer"});
$('#load-player i').removeClass('fab fa-youtube').addClass('fas fa-times-circle');
$('#player-container').removeClass('stack-bottom').addClass('stack-top');
//$('#player-panel').fadeTo(1000, 1);
$('#player-panel').fadeTo(0, 1);
$('#player-panel').animate({ width: $('#player-panel').css('max-width')}, 400);
} else {
if (interpreterData && interpreterData.open)
interpreterData.send({action: "hideplayer"});
$('#load-player i').removeClass('fas fa-times-circle').addClass('fab fa-youtube');
$('#player-container').removeClass('stack-top').addClass('stack-bottom');
//$('#player-panel').fadeTo(500, 0);
$('#player-panel').animate({ width: '0' }, 400);
$('#player-panel').fadeTo(0, 0);
}
});
$('#briefing-mode').on('click', function() {
console.log("Setup audio for breafing");
// Enable local microphone, if disabled
if (!isMicEnabled())
$('#toggle-microphone').trigger('click');
animateCSS('#toggle-microphone', 'heartBeat');
if (interpreterData && interpreterData.open)
interpreterData.send({action: "setaudiomode", mode: "briefing"});
if (speakerData && speakerData.open)
speakerData.send({action: "setaudiomode", mode: "briefing"});
});
$('#training-mode').on('click', function() {
// Disable local microphone, if enabled
console.log("Setup audio for training session");
if (isMicEnabled()) {
$('#toggle-microphone').trigger('click');
}
animateCSS('#toggle-microphone', 'heartBeat');
if (interpreterData && interpreterData.open)
interpreterData.send({action: "setaudiomode", mode: "training"});
if (speakerData && speakerData.open)
speakerData.send({action: "setaudiomode", mode: "training"});
});
$("input[data-toggle='tooltip']").mouseout(function(){
$(this).tooltip('hide');
});
$('#record-audio').on('click', function(e) {
console.log("Record clicked");
if ($("#record-audio > i").hasClass("fa-square")) {
console.log("Stop recording");
$("#record-audio > i").removeClass("fa-square").addClass("fa-circle");
audioRecorder.stop();
audioRecorder.getBuffers( saveAudio );
$("#save-audio").removeClass("disabled");
$("#save-audio > i").removeClass("fa-cog fa-spin").addClass("fa-save");
$("label[for='save-audio']").html("File ready");
} else {
console.log("Restart recording");
if (!audioRecorder) return;
$("#record-audio > i").removeClass("fa-circle").addClass("fa-square");
audioRecorder.clear();
audioRecorder.record();
$("#save-audio").addClass("disabled");
$("#save-audio > i").removeClass("fa-save").addClass("fa-cog fa-spin");
$("label[for='save-audio']").html("Recording…");
}
});
$('#save-audio').on('click', function(e) {
if ($(this).hasClass('disabled')) {
e.preventDefault();
} else {
console.log("Save audio file");
}
});
});
// Start/stop decalage timer when pressing space bar
$(document).keypress(function(e) {
if (e.target.id != 'chattext' && e.which == 32) {
$("#timer-startstop").trigger("click");
e.preventDefault();
}
});
function brownianNoise(g) {
var lastOut = 0.0;
var node = audioCtx.createScriptProcessor(1024, 2, 2);
node.onaudioprocess = function(e) {
var output = e.outputBuffer.getChannelData(0);
for (var i = 0; i < 1024; i++) {
var white = Math.random() * 2 - 1;
output[i] = (lastOut + (0.02 * white)) / 1.02;
lastOut = output[i];
output[i] *= g;
}
}
return node;
}
function brownianNoise2(g) {
var lastOut = 0.0;
var node = audioCtx.createBufferSource(),
buffer = audioCtx.createBuffer(1, 8192, audioCtx.sampleRate),
data = buffer.getChannelData(0);
for (var i = 0; i < 8192; i++) {
var white = Math.random() * 2 - 1;
data[i] = (lastOut + (0.03 * white)) / 1.02;
lastOut = data[i];
data[i] *= g;
}
node.buffer = buffer;
node.loop = true;
node.start(0);
return node;
}
function silence() {
var node = audioCtx.createBufferSource(),
buffer = audioCtx.createBuffer(1, 512, audioCtx.sampleRate),
data = buffer.getChannelData(0);
for (var i = 0; i < 512; i++) {
data[i] = 0;
}
node.buffer = buffer;
node.loop = true;
node.start(0);
return node;
}
function oscillator(freq = 11, vol = 0.01) {
var o = audioCtx.createOscillator();
o.type = "sine";
o.frequency = freq;
var g = audioCtx.createGain()
o.connect(g);
g.gain.exponentialRampToValueAtTime(vol, audioCtx.currentTime);
o.start();
return g;
}
function reconnectChannel(channel, stream) {
if (stream) {
} else {
}
}
function initCrossFader() {
if (typeof channel1 === "object" && channel1 != null) {
console.log("Disconnecting audio channel 1");
channel1.disconnect();
}
if (typeof channel2 === "object" && channel2 != null) {
console.log("Disconnecting audio channel 2");
channel2.disconnect();
}
if (speakerMedia && speakerMedia.open && speakerMediaStream) {
console.log("Adding speaker audio to crossfader...");
channel1 = audioCtx.createMediaStreamSource(speakerMediaStream);
} else {
console.log("Replacing speaker audio with brownian noise in the crossfader...");
channel1 = brownianNoise(0.0025);
}
if (interpreterMedia && interpreterMedia && interpreterMediaStream) {
console.log("Adding interpreter audio to crossfader...");
channel2 = audioCtx.createMediaStreamSource(interpreterMediaStream);
} else {
console.log("Replacing interpreter audio with brownian noise in the crossfader...");
channel2 = brownianNoise(0.0025);
}
if (swapChannels) {
var tmp = channel1;
channel1 = channel2;
channel2 = tmp;
}
channel1.connect(split1, 0, 0);
channel2.connect(split2, 0, 0);
split1.connect(gain1);
split2.connect(gain2);
gain1.connect(mix, 0, 1);
gain2.connect(mix, 0, 0);
mix.connect(audioCtx.destination);
}
function initRecorder() {
mixrec = audioCtx.createChannelMerger(2, 2); // Channel mixer for the recorder
audioRecorder = new Recorder( mixrec );
zeroGain = audioCtx.createGain();
split1.connect(mixrec, 0, 1);
split2.connect(mixrec, 0, 0);
// Connect to a gain node with gain value = 0
// so it will be silent and then to destination
// to activate the audio flow
zeroGain.gain.value = 0.0;
mixrec.connect( zeroGain );
zeroGain.connect( audioCtx.destination );
}
// the ONLY time saveAudio is called is right after a
// new recording is completed, so here's where we should
// set up the download.
function saveAudio( buffers ) {
audioRecorder.exportWAV( doneEncoding );
}
function doneEncoding( blob ) {
var filename = appName + "-mixed-audio-file-" + ((recIndex<10)?"0":"") + recIndex + ".wav"
var url = Recorder.setupDownload( blob, filename, "save-audio");
console.log("Audio file created from blob:", url);
$("#recordings").append(
"<li class='list-group-item'><a href='" + url + "' download='" + filename + "'>" +
"record n. " + (recIndex) + " (" + blob.size + " bytes)</a></li>"
);
recIndex++;
}
// Sets the MediaStream as the video element src.
function gotLocalMediaStream(mediaStream) {
// Save local microphone and camera status