-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2174 lines (1838 loc) · 83.1 KB
/
script.js
File metadata and controls
2174 lines (1838 loc) · 83.1 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
/**
* Enhanced Spatial Audio Implementation
*
* ==== TIMING DOCUMENTATION SUMMARY ====
*
* This application uses HARDCODED timing values for 4 different musical movements.
* All timing values are defined in the timestampPatterns object (lines ~70-160).
*
* TIMING SOURCES:
* 1. PRIMARY: timestampPatterns object in this file (script.js) - ACTIVELY USED
* 2. REFERENCE: /timings/*.txt files - for development reference only, NOT used by app
*
* MOVEMENT TIMING BREAKDOWN:
*
* 1. DEFAULT (Double Clarinet):
* - 27 timing points from 0 to 68.79 seconds
* - Simple pattern switching between 6 speakers
* - Timings: timestampPatterns.default.timestamps (line ~76)
*
* 2. TRANSITION 1-2:
* - 25 timing points from 0 to 56.929 seconds
* - Special decay behavior - speakers fade to 0.5 instead of 0
* - Timings: timestampPatterns["transition1-2"].timestamps (line ~90)
*
* 3. TRANSITION 3-4:
* - 5 timing points from 0 to 55.5 seconds
* - Uses CIRCULAR PANNING with acceleration over time
* - Rotation speed controlled in animateCircularPanning() (line ~1020)
* - Timings: timestampPatterns["transition3-4"].timestamps (line ~140)
*
* 4. STROPHE V:
* - 10 timing points from 0 to 9 seconds (simplified for demo)
* - Uses DRY/WET mixing between performer and hidden speaker
* - Automatic crossfading controlled in updateDryWetBalance() (line ~1080)
* - Timings: timestampPatterns.stropheV.timestamps (line ~150)
*
* TIMING CONTROL FUNCTIONS:
* - startPatternSwitching(): Main timing loop (50ms intervals)
* - animateCircularPanning(): Controls rotation speed for transition3-4
* - updateDryWetBalance(): Controls crossfading for StropheV
* - setInitialSpeakerGains(): Sets starting conditions for each movement
*/
// Create variables to hold audio components (initialized on user interaction)
let audioCtx = null;
let audioSource = null;
let gainNodes = [];
let masterGain = null;
let panners = [];
let audioInitialized = false;
// Set constants for audio positioning
const posX = 0, posY = 1.7, posZ = 0;
// Application states
let currentMode = 'audience'; // Default to audience mode
let currentScene = 'default';
let isMixingMode = false;
let toggleMin3DViewBtn = null; // Declare variable for the toggle button
let currentPerformerSpeakerIndex = 0;
// Audio effects for special scenes
let circularPanner = null;
let accelerationFactor = 1.0;
let resonator = null;
let dryWetMixer = null;
let wetGain = null;
let dryGain = null;
// Strophe V specific variables
let stropheWetAudioElement = null;
let stropheWetAudioSource = null;
let wetPanners = []; // Separate panners for wet signal
let wetGainNodes = []; // Separate gain nodes for wet signal
let manualWetAmount = 0; // 0-1, controlled by engineer
let isStropheVPlaying = false;
let hiddenSpeakerPosition = null; // Position of the hidden speaker for wet signal
let performerDryPanner = null; // Panner for the performer (dry signal)
let hiddenWetPanner = null; // Panner for the hidden speaker (wet signal)
// Track which audio elements have already been connected to sources
let connectedAudioElements = new Set();
// Audio elements
let audioElements = {};
let currentAudioElement = null;
// Animation frames
let animationFrameId = null;
// Get the audio elements after DOM load
document.addEventListener('DOMContentLoaded', () => {
audioElements = {
'default': document.getElementById('double'),
'transition1-2': document.getElementById('transition1-2'),
'transition3-4': document.getElementById('transition3-4'),
'stropheV': document.getElementById('stropheV'),
}
currentAudioElement = audioElements['default'];
window.audioElement = currentAudioElement;
// Get the wet audio element for Strophe V
stropheWetAudioElement = document.getElementById('stropheV-wet');
});
// Audio timestamps and patterns - MAIN TIMING DEFINITIONS FOR ALL MOVEMENTS
const timestampPatterns = {
default: {
// DOUBLE CLARINET MOVEMENT TIMINGS (default scene)
// These timestamps are HARDCODED in seconds for the double clarinet piece
// Each timestamp corresponds to when the audio pattern should change
// Total duration: ~68.79 seconds with 27 different timing points
timestamps: [
0, 1.483, 3.311, 4.59, 7.863, 11.365, 17.314, 18.926, 23.75,
31.035, 33.334, 36.547, 37.723, 40.114, 41.014, 42.203, 43.957,
45.172, 45.783, 47.39, 48.731, 50.323, 52.462, 55.005, 59.489,
63.377, 68.79
],
// DOUBLE CLARINET MOVEMENT SPEAKER PATTERNS
// Each pattern array corresponds to the 6 speakers in hexagonal arrangement
// [speaker1, speaker2, speaker3, speaker4, speaker5, speaker6]
// 1 = active, 0 = inactive for each timestamp above
// 27 patterns total matching the 27 timestamps
patterns: [
[1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1],
[0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [1, 0, 0, 0, 0, 1],
[1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1],
[0, 1, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0],
[1, 1, 0, 0, 1, 0], [1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 1], [1, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]
]
},
"transition1-2": {
// TRANSITION 1-2 MOVEMENT TIMINGS
// These timestamps are HARDCODED in seconds for the transition1-2 piece
// Corresponds to audio file: audio/transition12.mp3
// Total duration: ~56.929 seconds with 25 different timing points
// This movement has special gain behavior - speakers decay to 0.5 instead of 0
timestamps: [
0.000, 8.238, 8.657, 10.897, 11.442, 12.834, 13.283, 16.761,
17.966, 18.536, 19.240, 21.339, 22.231, 26.715, 27.833,
29.779, 30.296, 38.051, 38.437, 40.586, 41.628, 47.053,
47.710, 56.151, 56.929
],
// TRANSITION 1-2 SPEAKER PATTERNS
// Each pattern corresponds to timing above - 25 patterns total
// Comments show which speaker number is active (1-6)
// This movement uses special gain decay logic in applyPattern()
patterns: [
[1, 1, 1, 1, 1, 1], // all
[0, 0, 0, 0, 0, 1], // 6
[0, 0, 0, 0, 0, 1], // 6
[0, 0, 0, 0, 1, 0], // 5
[0, 0, 0, 0, 1, 0], // 5
[0, 1, 0, 0, 0, 0], // 2
[0, 1, 0, 0, 0, 0], // 2
[0, 0, 1, 0, 0, 0], // 3
[0, 0, 1, 0, 0, 0], // 3
[0, 0, 0, 1, 0, 0], // 4
[0, 0, 0, 1, 0, 0], // 4
[1, 0, 0, 0, 0, 0], // 1
[1, 0, 0, 0, 0, 0], // 1
[0, 1, 0, 0, 0, 0], // 2
[0, 1, 0, 0, 0, 0], // 2
[1, 0, 0, 0, 0, 0], // 1
[1, 0, 0, 0, 0, 0], // 1
[0, 0, 1, 0, 0, 0], // 3
[0, 0, 1, 0, 0, 0], // 3
[0, 0, 0, 0, 1, 0], // 5
[0, 0, 0, 0, 1, 0], // 5
[0, 0, 0, 0, 0, 1], // 6
[0, 0, 0, 0, 0, 1], // 6
[0, 0, 0, 1, 0, 0], // 4
[0, 0, 0, 1, 0, 0] // 4
]
},
"transition3-4": {
// TRANSITION 3-4 MOVEMENT TIMINGS
// These timestamps are HARDCODED for the transition3-4 piece
// Corresponds to audio file: audio/transition34.mp3
// Only 5 timing points - this movement uses CIRCULAR PANNING effect
// The circular rotation speed accelerates over time (see animateCircularPanning())
timestamps: [0, 14.700, 50.00, 53.000, 55.500],
// Special rotating pattern handled by circular panner
// These patterns are overridden by the circular panning algorithm
// The actual audio moves in a circle around all 6 speakers
patterns: [
[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1],
]
},
"stropheV": {
// STROPHE V MOVEMENT TIMINGS
// These timestamps are HARDCODED for the Strophe V piece
// Corresponds to audio files: audio/strophe5dry.mp3 and audio/strophe5wet.mp3
// Simple 1-second intervals for demonstration - 10 timing points total
// This movement uses DRY/WET MIXING with performer + hidden speaker
timestamps: [0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
// STROPHE V SPEAKER PATTERNS
// Note: These patterns are largely decorative as the actual audio comes from:
// - Performer position (dry signal at 100%)
// - Hidden speaker behind speakers 1&2 (wet signal, controllable 0-100%)
patterns: [
[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1],
[1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 1]
]
}
};
// Make current timestamps and patterns available globally
window.timestamps = timestampPatterns.default.timestamps;
window.presets = timestampPatterns.default.patterns;
// Mode-specific positions
const modePositions = {
engineer: { x: 0, y: 2.5, z: 0 }, // Center of the room, slightly higher, not too high
audience: { x: 0, y: 1.7, z: 2 } // Back of the room
};
// Pattern switching variables
let patternInterval = null;
let currentPatternIndex = 0;
const speakerPositions = [
{ angle: 210, x: -6.1, y: 1.7, z: -3.5 }, // Speaker 1 (left front)
{ angle: 150, x: 6.1, y: 1.7, z: -3.5 }, // Speaker 2 (right front)
{ angle: 90, x: 7, y: 1.7, z: 0 }, // Speaker 3 (right)
{ angle: 30, x: 6.1, y: 1.7, z: 3.5 }, // Speaker 4 (right back)
{ angle: 330, x: -6.1, y: 1.7, z: 3.5 }, // Speaker 5 (left back)
{ angle: 270, x: -7, y: 1.7, z: 0 } // Speaker 6 (left)
];
// UI Controls
const playPauseButton = document.getElementById('playPauseButton');
const resetButton = document.getElementById('resetButton');
const arabicPlayhead = document.getElementById('arabic-playhead'); // Get the new playhead element
const arabicContainer = document.getElementById('arabic-visualization-container'); // Get the container
const volumeDisplayPanel = document.getElementById('volume-display-panel');
const volumeDisplayBtn = document.getElementById('volumeDisplayBtn');
const closeVolumePanel = document.getElementById('closeVolumePanel');
const scorePanel = document.getElementById('score-panel');
const scoreImage = document.getElementById('score-image');
const scoreDisplayBtn = document.getElementById('scoreDisplayBtn');
if (!playPauseButton) console.error("Play/Pause button not found!");
if (!resetButton) console.error("Reset button not found!");
if (!arabicPlayhead) console.error("Arabic playhead element not found!");
if (!arabicContainer) console.error("Arabic visualization container not found!");
if (!scorePanel) console.error("Score panel not found!");
if (!scoreImage) console.error("Score image not found!");
if (!scoreDisplayBtn) console.error("Score display button not found!");
// Use a simple flag to track initialization attempts
let initializationAttempted = false;
// Function to initialize audio context with user gesture
function initAudioContext() {
if (audioCtx) return Promise.resolve(); // Already initialized
console.log("Initializing Audio Context...");
return new Promise((resolve, reject) => {
try {
// Create audio context
const AudioContext = window.AudioContext || window.webkitAudioContext;
audioCtx = new AudioContext({ latencyHint: 'interactive' });
// Make globally accessible
window.audioCtx = audioCtx;
window.listener = audioCtx.listener;
// Configure basic settings immediately
audioCtx.destination.channelCount = audioCtx.destination.maxChannelCount;
audioCtx.destination.channelCountMode = "explicit";
audioCtx.destination.channelInterpretation = "speakers";
// Set listener position and orientation based on mode
updateListenerPosition();
console.log("Audio Context created. Setting up Web Audio...");
// Set up audio connections
setupWebAudio().then(() => {
audioInitialized = true;
console.log("Audio fully initialized!");
resolve();
}).catch(error => {
console.error("Error during Web Audio setup:", error);
// Still resolve since we at least have the AudioContext
resolve();
});
} catch (error) {
console.error("Failed to create Audio Context:", error);
reject(error);
}
});
}
// Update listener position based on current mode
function updateListenerPosition() {
if (!audioCtx || !audioCtx.listener) return;
let position;
// For performer mode, use the position of the selected speaker
if (currentMode === 'performer' && speakerPositions[currentPerformerSpeakerIndex]) {
position = speakerPositions[currentPerformerSpeakerIndex];
} else {
position = modePositions[currentMode];
}
// const position = modePositions[currentMode];
// Set listener position
const listener = audioCtx.listener;
if (listener.positionX) {
// Modern API
listener.positionX.value = position.x;
listener.positionY.value = position.y;
listener.positionZ.value = position.z;
} else {
// Fallback for older browsers
listener.setPosition(position.x, position.y, position.z);
}
// Set forward orientation based on mode
let forwardX = 0, forwardY = 0, forwardZ = -1;
if (currentMode === 'audience') {
forwardZ = -1; // facing forward
}
if (listener.forwardX) {
// Modern API
listener.forwardX.value = forwardX;
listener.forwardY.value = forwardY;
listener.forwardZ.value = forwardZ;
listener.upX.value = 0;
listener.upY.value = 1;
listener.upZ.value = 0;
} else {
// Fallback
listener.setOrientation(forwardX, forwardY, forwardZ, 0, 1, 0);
}
}
// Function to set up all the Web Audio connections
function setupWebAudio() {
return new Promise((resolve, reject) => {
if (!audioCtx || !currentAudioElement) {
reject(new Error("Missing AudioContext or audio element"));
return;
}
// --- FIX: Always create a fresh <audio> element for the current scene ---
// This avoids the "already connected" error by ensuring a new HTMLMediaElement each time.
// Remove the old element from DOM if it exists
if (currentAudioElement && currentAudioElement.parentNode) {
currentAudioElement.parentNode.removeChild(currentAudioElement);
}
// Create a new audio element with the same src as the scene's audio
const newAudio = document.createElement('audio');
newAudio.id = currentScene;
newAudio.src = audioElements[currentScene].src;
newAudio.preload = "auto";
newAudio.crossOrigin = "anonymous";
// Insert the new audio element into the DOM (so MediaElementSource works)
document.body.appendChild(newAudio);
// Update references
audioElements[currentScene] = newAudio;
currentAudioElement = newAudio;
window.audioElement = currentAudioElement;
// For Strophe V, also create the wet audio element
if (currentScene === 'stropheV' && stropheWetAudioElement) {
// Remove old wet element if it exists
if (stropheWetAudioElement.parentNode) {
stropheWetAudioElement.parentNode.removeChild(stropheWetAudioElement);
}
// Create a new wet audio element
const newWetAudio = document.createElement('audio');
newWetAudio.id = 'stropheV-wet';
newWetAudio.src = 'audio/strophe5wet.mp3';
newWetAudio.preload = "auto";
newWetAudio.crossOrigin = "anonymous";
document.body.appendChild(newWetAudio);
stropheWetAudioElement = newWetAudio;
}
// Now create the MediaElementSourceNode for the new element
try {
audioSource = audioCtx.createMediaElementSource(currentAudioElement);
connectedAudioElements.add(currentAudioElement);
// For Strophe V, also create the wet audio source
if (currentScene === 'stropheV' && stropheWetAudioElement) {
stropheWetAudioSource = audioCtx.createMediaElementSource(stropheWetAudioElement);
connectedAudioElements.add(stropheWetAudioElement);
}
// Continue with the rest of the setup
createAudioGraph().then(resolve).catch(reject);
} catch (e) {
console.error("Error creating media element source:", e);
reject(e);
return;
}
});
}
// Function to create the audio graph (extracted from setupWebAudio for clarity)
function createAudioGraph() {
return new Promise((resolve, reject) => {
try {
// Create 6 audio sources in a hexagonal arrangement
const speakerRadius = 7;
const sources = Array.from({ length: 6 }, (_, i) => getHexPosition(i, speakerRadius));
// Create simplified panners
panners = sources.map(source => {
return new PannerNode(audioCtx, {
panningModel: "HRTF",
distanceModel: "inverse",
positionX: source.x,
positionY: source.y,
positionZ: source.z,
refDistance: 2,
maxDistance: 10
});
});
// Create gain nodes and master gain
gainNodes = panners.map(() => new GainNode(audioCtx, { gain: 0 }));
window.gainNodes = gainNodes;
masterGain = new GainNode(audioCtx, { gain: 0.8 });
// For Strophe V, create additional panners and gain nodes for wet signal
if (currentScene === 'stropheV') {
wetPanners = sources.map(source => {
return new PannerNode(audioCtx, {
panningModel: "HRTF",
distanceModel: "inverse",
positionX: source.x,
positionY: source.y,
positionZ: source.z,
refDistance: 2,
maxDistance: 10
});
});
wetGainNodes = wetPanners.map(() => new GainNode(audioCtx, { gain: 0 }));
}
// Create circular panner for Transition 3-4
setupCircularPanner();
// Create resonator for Strophe V
setupResonator();
// Connect everything together
connectAudioNodes();
// Set initial gains
setInitialSpeakerGains();
console.log("Spatial audio setup complete");
resolve();
} catch (e) {
console.error("Error setting up spatial audio:", e);
// Create a fallback direct connection if spatial setup fails
try {
console.log("Creating fallback direct audio connection");
audioSource.connect(audioCtx.destination);
resolve();
} catch (fallbackError) {
reject(fallbackError);
}
}
});
}
// Function to calculate hexagonal speaker positions
function getHexPosition(index, radius) {
const speakerAngles = [210, 150, 90, 30, 330, 270];
const angle = (speakerAngles[index] * Math.PI) / 180;
return {
x: radius * Math.sin(angle),
y: posY,
z: radius * Math.cos(angle)
};
}
// Setup circular panner for transition 3-4
// TIMING SETUP: Define base parameters for circular panning movement
function setupCircularPanner() {
if (!audioCtx) return;
// Create a gain node to control the circular panning effect
circularPanner = {
angle: 0, // Starting angle (0 radians)
speed: 0.5, // BASE ROTATION SPEED (multiplied by acceleration in animateCircularPanning)
active: false // Whether circular panning is currently active
};
}
// Setup dry/wet mixing for Strophe V
// INITIAL TIMING SETUP: Define starting balance between performer and hidden speaker
function setupResonator() {
if (!audioCtx) return;
// Create dry/wet mixer gain nodes
dryGain = audioCtx.createGain();
wetGain = audioCtx.createGain();
// STROPHE V INITIAL TIMING VALUES:
// Initialize with performer fully audible and wet signal at 50%
dryGain.gain.value = 1.0; // 100% dry (performer) - always audible
wetGain.gain.value = 0.5; // 50% wet at start - will increase over time via updateDryWetBalance()
// SPATIAL POSITIONING: Create a position for the hidden speaker BEHIND speakers 1 and 2, slightly elevated
// Speakers 1 and 2 are at:
// Speaker 1: { x: -6.1, y: 1.7, z: -3.5 }
// Speaker 2: { x: 6.1, y: 1.7, z: -3.5 }
// Hidden speaker should be further back (more negative z) and between them
hiddenSpeakerPosition = {
x: (speakerPositions[0].x + speakerPositions[1].x) / 2, // Between speakers 1 and 2 (x=0)
y: 5, // Slightly elevated above speaker level
z: -11 // Behind speakers 1 and 2 (they're at z=-3.5, so go further back)
};
console.log("Dry/wet mixer setup complete for Strophe V with performer and hidden speaker positioning");
}
// Connect audio nodes based on the current scene
function connectAudioNodes() {
if (!audioSource || !audioCtx) return;
// Clear existing connections
try {
audioSource.disconnect();
if (stropheWetAudioSource) stropheWetAudioSource.disconnect();
panners.forEach(panner => panner.disconnect());
gainNodes.forEach(gain => gain.disconnect());
if (wetPanners.length) wetPanners.forEach(panner => panner.disconnect());
if (wetGainNodes.length) wetGainNodes.forEach(gain => gain.disconnect());
if (resonator) resonator.disconnect();
if (dryGain) dryGain.disconnect();
if (wetGain) wetGain.disconnect();
if (masterGain) masterGain.disconnect();
} catch (e) {
// Ignore disconnect errors
}
if (currentScene === "stropheV") {
// Strophe V uses the performer as the dry source and a hidden speaker for the wet signal
if (stropheWetAudioSource) {
// Set up performer position panner for dry signal (always at 100%)
const performerPanner = audioCtx.createPanner();
performerPanner.panningModel = 'HRTF';
performerPanner.distanceModel = 'inverse';
performerPanner.refDistance = 1;
performerPanner.maxDistance = 10000;
performerPanner.rolloffFactor = 1;
// Position the performer at the red circle location
performerPanner.positionX.value = 0;
performerPanner.positionY.value = -0.06; // Slightly below ground level like the red circle
performerPanner.positionZ.value = -4.111; // Red circle position
// Connect dry source (performer) directly to master at full volume
audioSource.connect(performerPanner);
performerPanner.connect(dryGain);
dryGain.connect(masterGain);
// Set up hidden speaker panner for wet signal only
const hiddenSpeakerPanner = audioCtx.createPanner();
hiddenSpeakerPanner.panningModel = 'HRTF';
hiddenSpeakerPanner.distanceModel = 'inverse';
hiddenSpeakerPanner.refDistance = 1;
hiddenSpeakerPanner.maxDistance = 10000;
hiddenSpeakerPanner.rolloffFactor = 1;
// Position the hidden speaker between speakers 1 and 2, slightly elevated
hiddenSpeakerPanner.positionX.value = hiddenSpeakerPosition.x;
hiddenSpeakerPanner.positionY.value = hiddenSpeakerPosition.y;
hiddenSpeakerPanner.positionZ.value = hiddenSpeakerPosition.z;
// Connect wet source through hidden speaker panner to wet gain
stropheWetAudioSource.connect(hiddenSpeakerPanner);
hiddenSpeakerPanner.connect(wetGain);
wetGain.connect(masterGain);
// Store these panners for potential future adjustments
performerDryPanner = performerPanner;
hiddenWetPanner = hiddenSpeakerPanner;
console.log("Strophe V setup: Performer (dry) and hidden speaker (wet) configuration active");
} else {
// Fallback to single source if wet source isn't available
panners.forEach((panner, index) => {
audioSource.connect(panner);
panner.connect(gainNodes[index]);
gainNodes[index].connect(masterGain);
});
}
} else {
// Basic connection for all other scenes
panners.forEach((panner, index) => {
audioSource.connect(panner);
panner.connect(gainNodes[index]);
gainNodes[index].connect(masterGain);
});
}
masterGain.connect(audioCtx.destination);
}
// Abstracted function to play a pattern on speakers
function playSpeaker(pattern) {
if (!gainNodes.length) return;
// For Strophe V, we don't adjust the visible speaker gains
// as audio comes from performer and hidden speaker only
if (currentScene === 'stropheV') {
// We still need to update the visualization for visual feedback
if (window.updateVisualization3D) {
window.updateVisualization3D(gainNodes);
// For visualization purposes, we might want to indicate the hidden speaker position
if (window.updateHiddenSpeakerVisualization && hiddenSpeakerPosition) {
window.updateHiddenSpeakerVisualization(hiddenSpeakerPosition);
}
}
return;
}
// For all other scenes, adjust visible speaker gains
pattern.forEach((gain, idx) => {
if (gainNodes[idx]) {
gainNodes[idx].gain.setTargetAtTime(gain, audioCtx ? audioCtx.currentTime : 0, 0.1);
}
});
// Update 3D visualization if available
if (window.updateVisualization3D) {
window.updateVisualization3D(gainNodes);
}
}
// Simplified play/pause handler
function togglePlayback() {
// Check if audio element exists
if (!currentAudioElement) {
console.error("Audio element not found!");
alert("Audio element not found. Check the HTML structure.");
return;
}
console.log("Toggle playback called");
// Initialize audio if needed
if (!audioCtx) {
initAudioContext().then(() => {
actuallyTogglePlayback();
}).catch(error => {
console.error("Failed to initialize audio:", error);
// Try direct playback as last resort
tryDirectPlayback();
});
} else {
// Resume context if needed
if (audioCtx.state === 'suspended') {
audioCtx.resume().then(() => {
actuallyTogglePlayback();
}).catch(error => {
console.error("Failed to resume audio context:", error);
tryDirectPlayback();
});
} else {
actuallyTogglePlayback();
}
}
}
// Function to actually handle play/pause state
function actuallyTogglePlayback() {
if (playPauseButton.dataset.playing === 'false') {
console.log("Attempting to play audio...");
if (currentScene === 'stropheV' && stropheWetAudioElement) {
// For Strophe V, synchronize both dry and wet audio
playStropheVSynchronized();
} else {
// Normal single audio playback
const playPromise = currentAudioElement.play();
if (playPromise !== undefined) {
playPromise.then(() => {
console.log("Audio playback started successfully!");
playPauseButton.dataset.playing = 'true';
playPauseButton.style.setProperty('--play-pause-icon', '"\\23F8"');
playPauseButton.title = "Pause Audio";
if (audioInitialized) {
startPatternSwitching();
startSpecialEffects();
}
}).catch(error => {
console.error("Error playing audio:", error);
tryDirectPlayback();
});
}
}
} else {
console.log("Pausing audio");
if (currentScene === 'stropheV' && stropheWetAudioElement) {
// Pause both dry and wet audio for Strophe V
currentAudioElement.pause();
stropheWetAudioElement.pause();
isStropheVPlaying = false;
} else {
currentAudioElement.pause();
}
playPauseButton.dataset.playing = 'false';
playPauseButton.style.setProperty('--play-pause-icon', '"\\25B6"');
playPauseButton.title = "Play Audio";
stopPatternSwitching();
stopSpecialEffects();
}
}
// Function to play both dry and wet audio for Strophe V in sync
function playStropheVSynchronized() {
// Set both audio elements to the same time
const currentTime = currentAudioElement.currentTime;
stropheWetAudioElement.currentTime = currentTime;
// Play both simultaneously
const dryPromise = currentAudioElement.play();
const wetPromise = stropheWetAudioElement.play();
Promise.all([dryPromise, wetPromise]).then(() => {
console.log("Strophe V synchronized playback started!");
playPauseButton.dataset.playing = 'true';
playPauseButton.style.setProperty('--play-pause-icon', '"\\23F8"');
playPauseButton.title = "Pause Audio";
isStropheVPlaying = true;
if (audioInitialized) {
startPatternSwitching();
startSpecialEffects();
startStropheVCrossfading();
}
}).catch(error => {
console.error("Error playing Strophe V synchronized audio:", error);
tryDirectPlayback();
});
}
// Last resort direct playback
function tryDirectPlayback() {
console.log("Attempting direct playback as fallback");
// Unmute and set volume explicitly
currentAudioElement.muted = false;
currentAudioElement.volume = 1.0;
// Add inline event listeners for this attempt
const successListener = () => {
console.log("Direct playback successful!");
playPauseButton.dataset.playing = 'true';
playPauseButton.style.setProperty('--play-pause-icon', '"\\23F8"');
currentAudioElement.removeEventListener('play', successListener);
};
const errorListener = (e) => {
console.error("Direct playback failed:", e);
currentAudioElement.removeEventListener('error', errorListener);
alert("Could not play audio. Please check if the audio file exists and try again.");
};
currentAudioElement.addEventListener('play', successListener);
currentAudioElement.addEventListener('error', errorListener);
// Try to play with a slight delay
setTimeout(() => {
try {
const promise = currentAudioElement.play();
if (promise) {
promise.catch(e => console.error("Promise rejection in direct play:", e));
}
} catch (e) {
console.error("Exception in direct play:", e);
}
}, 300);
}
// Connect the play button to the toggle function
playPauseButton.addEventListener('click', togglePlayback);
// Reset button functionality
resetButton.addEventListener('click', () => {
const wasPlaying = playPauseButton.dataset.playing === 'true';
currentAudioElement.pause();
currentAudioElement.currentTime = 0;
// For Strophe V, also reset the wet audio element
if (currentScene === 'stropheV' && stropheWetAudioElement) {
stropheWetAudioElement.pause();
stropheWetAudioElement.currentTime = 0;
isStropheVPlaying = false;
}
updateArabicPlayhead(); // Reset playhead position
playPauseButton.dataset.playing = 'false';
playPauseButton.style.setProperty('--play-pause-icon', '"\\25B6"');
currentPatternIndex = 0;
applyPattern(currentPatternIndex);
stopPatternSwitching();
stopSpecialEffects();
// Reset dry/wet control to initial state (50/50 mix for Strophe V)
if (currentScene === 'stropheV') {
setDryWetAmount(0.5); // Start at 50% wet (both playing)
}
if (window.visualizer3D) {
window.visualizer3D.resetOrientation();
}
if (wasPlaying) {
setTimeout(() => playPauseButton.click(), 50);
}
});
// Handle document click to initialize audio on any user interaction
document.addEventListener('click', event => {
// Only initialize once and only for actual user clicks (not programmatic)
if (!initializationAttempted && event.isTrusted) {
initializationAttempted = true;
initAudioContext().catch(e => console.error("Initialization on click failed:", e));
}
// Also try to resume the context if it exists but is suspended
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume().catch(e => console.error("Failed to resume on click:", e));
}
});
// Track speaker states for transition1-2
let t12SpeakerStates = null; // null or array of { state: "idle"|"active"|"decaying" }
function resetT12SpeakerStates() {
t12SpeakerStates = Array(6).fill().map(() => ({ state: "idle" }));
}
// Set initial gain values
// INITIAL TIMING SETUP: Different movements start with different speaker configurations
function setInitialSpeakerGains() {
if (!gainNodes.length) return;
if (currentScene === "transition1-2") {
// TRANSITION 1-2 INITIAL TIMING: All speakers start at 50% volume (0.5)
// This is different from other movements - creates the baseline for decay behavior
const initialGains = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5];
gainNodes.forEach((gain, idx) => {
gain.gain.setValueAtTime(initialGains[idx], audioCtx.currentTime);
});
resetT12SpeakerStates();
// Update 3D visualization if available
if (window.updateVisualization3D) {
window.updateVisualization3D(gainNodes);
}
} else {
// DEFAULT/OTHER MOVEMENTS INITIAL TIMING: Only speaker 1 starts active at 50%
// [speaker1, speaker2, speaker3, speaker4, speaker5, speaker6]
const initialGains = [0.5, 0,0,0,0,0];
playSpeaker(initialGains);
}
}
// Function to update the position of the Arabic playhead
function updateArabicPlayhead() {
if (!currentAudioElement || !arabicPlayhead) return;
const duration = currentAudioElement.duration;
const currentTime = currentAudioElement.currentTime;
if (duration > 0) {
const percentage = (currentTime / duration) * 100;
arabicPlayhead.style.left = `${percentage}%`;
} else {
arabicPlayhead.style.left = '0%';
}
}
// Function to handle seeking audio when clicking the visualization container
function handleSeek(event) {
console.log("handleSeek called"); // Log entry
if (!currentAudioElement || !arabicContainer) {
console.log("handleSeek: Missing audio element or container");
return;
}
// Check if duration is valid and available
if (!currentAudioElement.duration || currentAudioElement.duration <= 0 || isNaN(currentAudioElement.duration)) {
console.log("handleSeek: Audio duration not available or invalid:", currentAudioElement.duration);
// Potentially wait for metadata if needed, or just return
return;
}
// Check readyState - HAVE_METADATA (1) is minimum for duration, might need more for seeking smoothly
if (currentAudioElement.readyState < 1) {
console.log("handleSeek: Audio not ready for seeking. readyState:", currentAudioElement.readyState);
// You might want to wait for 'canplay' or 'canplaythrough' event if this happens often
return;
}
// Get the bounding rectangle of the container
const rect = arabicContainer.getBoundingClientRect();
// Calculate the click position relative to the container's left edge
const clickX = event.clientX - rect.left;
// Calculate the percentage position within the container
const percentage = Math.max(0, Math.min(1, clickX / rect.width));
// Calculate the new time based on the percentage and duration
const newTime = percentage * currentAudioElement.duration;
console.log(`handleSeek: Seeking to ${newTime.toFixed(3)}s (${(percentage * 100).toFixed(1)}%)`); // Log seek details
// Set the audio's current time
try {
// Ensure the new time is within valid bounds (important for some browsers/formats)
const clampedTime = Math.max(0, Math.min(newTime, currentAudioElement.duration));
currentAudioElement.currentTime = clampedTime;
// For Strophe V, also set the wet audio element's time
if (currentScene === 'stropheV' && stropheWetAudioElement) {
stropheWetAudioElement.currentTime = clampedTime;
}
console.log("handleSeek: currentTime set successfully to:", clampedTime); // Log success
} catch (e) {
console.error("handleSeek: Error setting currentTime:", e); // Log error
return; // Stop if setting time failed
}
// Immediately update the playhead position
updateArabicPlayhead();
// Always apply the pattern for the new time immediately after seeking
// This ensures the visualization and audio spatialization update instantly.
console.log("handleSeek: Applying pattern for new time", newTime); // Log pattern application
const timestamps = timestampPatterns[currentScene].timestamps;
let newIndex = timestamps.findIndex((timestamp, index) => {
const nextTimestamp = timestamps[index + 1] || Infinity;
return newTime >= timestamp && newTime < nextTimestamp;
});
if (newIndex === -1) newIndex = 0; // Default to first pattern if not found
// Apply the pattern and update the current index
currentPatternIndex = newIndex;
playSpeaker(timestampPatterns[currentScene].patterns[newIndex]);
// Update 3D visualization as well
if (window.updateVisualization3D) {
window.updateVisualization3D(gainNodes);
}
}
// Start pattern switching
function startPatternSwitching() {
stopPatternSwitching();
patternInterval = setInterval(() => {
if (currentAudioElement.paused) return;
// Update Arabic playhead position
updateArabicPlayhead();
// Update volume display for transition1-2
if (currentScene === "transition1-2") {
updateVolumeDisplay();
}
// Special handling for Transition 3-4 (circular panning)
if (currentScene === 'transition3-4') {
return; // Skip normal pattern switching, handled by circular panning
}
const currentTime = currentAudioElement.currentTime;
const timestamps = timestampPatterns[currentScene].timestamps;