-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1381 lines (1198 loc) · 35.5 KB
/
Copy pathapp.js
File metadata and controls
1381 lines (1198 loc) · 35.5 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
/**
* SoundSwarm- Collaborative Music Creation
* Main Application Logic
*
* A web-based collaborative music application using the Web Audio API.
* Users can play notes from shared chord progressions and create
* ambient drones together.
*/
// ============================================
// Constants & Configuration
// ============================================
/**
* Note frequency lookup table (12-TET, A4 = 440Hz)
* Contains all notes from C1 to C8 with both sharp and flat notations
*/
const NOTE_FREQUENCIES = {
C1: 32.7,
"C#1": 34.65,
Db1: 34.65,
D1: 36.71,
"D#1": 38.89,
Eb1: 38.89,
E1: 41.2,
F1: 43.65,
"F#1": 46.25,
Gb1: 46.25,
G1: 49.0,
"G#1": 51.91,
Ab1: 51.91,
A1: 55.0,
"A#1": 58.27,
Bb1: 58.27,
B1: 61.74,
C2: 65.41,
"C#2": 69.3,
Db2: 69.3,
D2: 73.42,
"D#2": 77.78,
Eb2: 77.78,
E2: 82.41,
F2: 87.31,
"F#2": 92.5,
Gb2: 92.5,
G2: 98.0,
"G#2": 103.83,
Ab2: 103.83,
A2: 110.0,
"A#2": 116.54,
Bb2: 116.54,
B2: 123.47,
C3: 130.81,
"C#3": 138.59,
Db3: 138.59,
D3: 146.83,
"D#3": 155.56,
Eb3: 155.56,
E3: 164.81,
F3: 174.61,
"F#3": 185.0,
Gb3: 185.0,
G3: 196.0,
"G#3": 207.65,
Ab3: 207.65,
A3: 220.0,
"A#3": 233.08,
Bb3: 233.08,
B3: 246.94,
C4: 261.63,
"C#4": 277.18,
Db4: 277.18,
D4: 293.66,
"D#4": 311.13,
Eb4: 311.13,
E4: 329.63,
F4: 349.23,
"F#4": 369.99,
Gb4: 369.99,
G4: 392.0,
"G#4": 415.3,
Ab4: 415.3,
A4: 440.0,
"A#4": 466.16,
Bb4: 466.16,
B4: 493.88,
C5: 523.25,
"C#5": 554.37,
Db5: 554.37,
D5: 587.33,
"D#5": 622.25,
Eb5: 622.25,
E5: 659.25,
F5: 698.46,
"F#5": 739.99,
Gb5: 739.99,
G5: 783.99,
"G#5": 830.61,
Ab5: 830.61,
A5: 880.0,
"A#5": 932.33,
Bb5: 932.33,
B5: 987.77,
C6: 1046.5,
"C#6": 1108.73,
Db6: 1108.73,
D6: 1174.66,
"D#6": 1244.51,
Eb6: 1244.51,
E6: 1318.51,
F6: 1396.91,
"F#6": 1479.98,
Gb6: 1479.98,
G6: 1567.98,
"G#6": 1661.22,
Ab6: 1661.22,
A6: 1760.0,
"A#6": 1864.66,
Bb6: 1864.66,
B6: 1975.53,
C7: 2093.0,
"C#7": 2217.46,
Db7: 2217.46,
D7: 2349.32,
"D#7": 2489.02,
Eb7: 2489.02,
E7: 2637.02,
F7: 2793.83,
"F#7": 2959.96,
Gb7: 2959.96,
G7: 3135.96,
"G#7": 3322.44,
Ab7: 3322.44,
A7: 3520.0,
"A#7": 3729.31,
Bb7: 3729.31,
B7: 3951.07,
C8: 4186.01,
};
/**
* Chord presets - Collections of notes that sound good together
*/
const CHORD_PRESETS = {
Test: ["G3", "B3", "D4", "A4", "B4", "D5"],
BesideYouInTime: [
"D3",
"F3",
"A3",
"Bb3",
"D4",
"F4",
"A4",
"Bb4",
"D5",
"F5",
"A5",
],
CMajor: ["C3", "E3", "G3", "C4", "E4", "G4", "C5", "E5", "G5"],
GMajor: ["G3", "B3", "D4", "G4", "B4", "D5", "G5", "B5"],
DMajor: ["D3", "F#3", "A3", "D4", "F#4", "A4", "D5", "F#5", "A5"],
AmMaj7: ["A3", "C4", "E4", "G#4", "A4", "C5", "E5", "G#5"],
EmMaj7: ["E3", "G3", "B3", "D#4", "E4", "G4", "B4", "D#5"],
Dsus2: ["D3", "E3", "A3", "D4", "E4", "A4", "D5", "E5", "A5"],
Asus2: ["A2", "B2", "E3", "A3", "B3", "E4", "A4", "B4", "E5"],
Esus4: ["E3", "A3", "B3", "E4", "A4", "B4", "E5", "A5", "B5"],
Gmaj9: ["G3", "B3", "D4", "F#4", "A4", "G4", "B4", "D5", "F#5", "A5"],
};
/**
* Detune presets (in cents) for creating thicker sounds
*/
const DETUNE_PRESETS = {
low: [0, 8, -12],
medium: [0, 15, -20],
high: [0, 25, -35],
off: [0, 0, 0],
};
/**
* Audio timing constants - CRITICAL FOR CLICK-FREE TRANSITIONS
*/
const AUDIO_CONFIG = {
MIN_RAMP_TIME: 0.02, // Minimum time for any gain ramp to prevent clicks
FADE_OUT_DURATION: 0.4, // Standard fade out duration
FADE_IN_DURATION: 0.3, // Standard fade in duration
CROSSFADE_DURATION: 0.6, // Crossfade overlap duration
GLIDE_DURATION: 0.25, // Frequency glide duration
NEAR_ZERO: 0.0001, // Very small value to use instead of 0 for exponential ramps
OSC_ATTACK: 0.08, // Attack time for individual oscillators
OSC_RELEASE: 0.1, // Release time for individual oscillators
};
// ============================================
// State Variables
// ============================================
// Audio nodes
let audioContext;
let oscillators = [];
let lfos = [];
let gainNode, filterNode;
let lfoGain, volumeLfoGain, filterLfoGain;
let delayNode, delayFeedbackGain, dryGain, wetGain;
// Playback state
let isPlaying = false;
let currentNote = null;
let currentFrequency = 0;
let volumeLfoStartTime = 0;
let volumeLfoFrequency = 0;
// Settings
let currentWaveform = "sine";
let detuneEnabled = false;
let detuneIntensity = "medium";
let delayEnabled = false;
let visualizationEnabled = false;
let transitionMode = "glide";
// Session state
let sessionId = null;
let usedNotes = new Set();
let chordNotes = [];
let chordName = "Beside You in Time (NIN)";
let minChordFreq = 0;
let maxChordFreq = 0;
// Transition flag
let isTransitioning = false;
// Arpeggiator state
let arpeggiatorEnabled = false;
let arpeggiatorInterval = 5;
let arpeggiatorTimer = null;
// Audio unlock state (for iOS)
let audioUnlocked = false;
// Canvas
let canvas, ctx;
let dpr = window.devicePixelRatio || 1;
// Mobile detection
const isMobileDevice =
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
// DOM elements (cached for performance)
let noteDisplay, noteLabel, statusMessage, playButton, chordLabel;
let controlsSection, controlsOverlay, menuToggle, detuneDisplay;
let waveformButtons, detuneToggleButtons, detuneIntensityButtons;
let arpeggiatorToggleButtons, arpeggiatorIntervalButtons;
let visualizationToggleButtons, transitionButtons, shuffleNoteButton;
// Session save debounce
let saveSessionTimeout = null;
// ============================================
// Initialization
// ============================================
/**
* Initialize the application
*/
function init() {
// Cache DOM elements
cacheDOM();
// iOS Safari audio unlock - attach to MULTIPLE user interactions
const interactionHandler = async (e) => {
if (!audioUnlocked) {
await unlockAudio();
}
};
// Listen on multiple event types - iOS sometimes only responds to specific ones
document.addEventListener("touchstart", interactionHandler, {
capture: true,
});
document.addEventListener("touchend", interactionHandler, { capture: true });
document.addEventListener("click", interactionHandler, { capture: true });
document.addEventListener("mousedown", interactionHandler, { capture: true });
// Also try to unlock on the play button specifically
playButton.addEventListener("touchstart", interactionHandler, {
capture: true,
});
playButton.addEventListener("touchend", interactionHandler, {
capture: true,
});
parseURL();
setupCanvas();
setupControls();
requestNote();
window.addEventListener("resize", setupCanvas);
}
/**
* Cache DOM elements for performance
*/
function cacheDOM() {
canvas = document.getElementById("visualization");
ctx = canvas.getContext("2d");
noteDisplay = document.getElementById("noteDisplay");
noteLabel = document.getElementById("noteLabel");
statusMessage = document.getElementById("statusMessage");
playButton = document.getElementById("playButton");
chordLabel = document.getElementById("chordLabel");
controlsSection = document.getElementById("controlsSection");
controlsOverlay = document.getElementById("controlsOverlay");
menuToggle = document.getElementById("menuToggle");
detuneDisplay = document.getElementById("detuneDisplay");
waveformButtons = document.querySelectorAll("[data-waveform]");
detuneToggleButtons = document.querySelectorAll("[data-detune-toggle]");
detuneIntensityButtons = document.querySelectorAll("[data-detune]");
arpeggiatorToggleButtons = document.querySelectorAll(
"[data-arpeggiator-toggle]",
);
arpeggiatorIntervalButtons = document.querySelectorAll(
"[data-arpeggiator-interval]",
);
visualizationToggleButtons = document.querySelectorAll(
"[data-visualization-toggle]",
);
transitionButtons = document.querySelectorAll("[data-transition]");
shuffleNoteButton = document.getElementById("shuffleNoteButton");
}
// ============================================
// iOS Audio Unlock
// ============================================
/**
* Show debug info (helpful for iOS testing)
*/
function updateDebugInfo() {
const state = audioContext ? audioContext.state : "no context";
const unlocked = audioUnlocked ? "yes" : "no";
console.log(`Debug: state=${state}, unlocked=${unlocked}`);
// Uncomment the line below to show debug info on screen:
// statusMessage.textContent = `Audio: ${state} | Unlocked: ${unlocked}`;
}
/**
* Unlock audio for iOS Safari - must happen during user gesture
* Returns a promise that resolves when audio is ready
*/
async function unlockAudio() {
console.log("Attempting audio unlock...");
try {
// Create AudioContext if needed
if (!audioContext) {
const AudioContextClass =
window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) {
console.error("No AudioContext support");
return false;
}
audioContext = new AudioContextClass();
console.log("AudioContext created, state:", audioContext.state);
}
// Resume if suspended
if (audioContext.state === "suspended") {
console.log("Resuming suspended AudioContext...");
await audioContext.resume();
console.log("AudioContext resumed, state:", audioContext.state);
}
// iOS may need an oscillator to be started during user gesture
if (audioContext.state === "running" && !audioUnlocked) {
// Method 1: Silent oscillator
const oscillator = audioContext.createOscillator();
const silentGain = audioContext.createGain();
silentGain.gain.value = 0;
oscillator.connect(silentGain);
silentGain.connect(audioContext.destination);
oscillator.start(0);
oscillator.stop(audioContext.currentTime + 0.001);
// Method 2: Also try buffer source as backup
try {
const silentBuffer = audioContext.createBuffer(
1,
1,
audioContext.sampleRate,
);
const source = audioContext.createBufferSource();
source.buffer = silentBuffer;
source.connect(audioContext.destination);
source.start(0);
} catch (e) {
// Buffer method failed, but oscillator might have worked
}
audioUnlocked = true;
console.log("Audio unlocked successfully!");
updateDebugInfo();
}
return audioContext.state === "running";
} catch (e) {
console.error("Audio unlock error:", e);
updateDebugInfo();
return false;
}
}
// ============================================
// URL Parsing & Session Management
// ============================================
/**
* Parse URL parameters for session and chord configuration
*/
function parseURL() {
const params = new URLSearchParams(window.location.search);
// Session ID
sessionId = params.get("sid");
if (!sessionId) {
sessionId = "sess_" + Math.random().toString(36).substr(2, 9);
}
// Chord selection
const notesParam = params.get("notes");
const chordParam = params.get("chord");
if (notesParam) {
const notesList = notesParam
.split(",")
.map((n) => n.trim().replace("-sharp", "#").replace("-flat", "b"))
.filter((n) => NOTE_FREQUENCIES[n]);
if (notesList.length > 0) {
chordNotes = notesList;
chordName = "Custom";
} else {
chordNotes = CHORD_PRESETS["BesideYouInTime"];
}
} else if (chordParam && CHORD_PRESETS[chordParam]) {
chordNotes = CHORD_PRESETS[chordParam];
chordName = chordParam;
} else {
chordNotes = CHORD_PRESETS["Test"];
chordName = "Test";
}
chordLabel.textContent = `Chord: ${chordName}`;
// Calculate frequency range
const freqs = chordNotes.map((n) => NOTE_FREQUENCIES[n]);
minChordFreq = Math.min(...freqs);
maxChordFreq = Math.max(...freqs);
loadSession();
}
/**
* Load session data from localStorage
*/
function loadSession() {
const key = `soundswarm_${sessionId}`;
const stored = localStorage.getItem(key);
if (stored) {
try {
const data = JSON.parse(stored);
if (Array.isArray(data.usedNotes)) {
data.usedNotes.forEach((n) => usedNotes.add(n));
}
} catch (e) {
console.error("Failed to parse session:", e);
}
}
loadUserPreferences();
}
/**
* Load user preferences from localStorage
*/
function loadUserPreferences() {
const prefsKey = "soundswarm_preferences";
const stored = localStorage.getItem(prefsKey);
if (stored) {
try {
const prefs = JSON.parse(stored);
if (prefs.waveform) currentWaveform = prefs.waveform;
if (prefs.detuneEnabled !== undefined)
detuneEnabled = prefs.detuneEnabled;
if (prefs.detuneIntensity) detuneIntensity = prefs.detuneIntensity;
if (prefs.arpeggiatorEnabled !== undefined)
arpeggiatorEnabled = prefs.arpeggiatorEnabled;
if (prefs.arpeggiatorInterval)
arpeggiatorInterval = prefs.arpeggiatorInterval;
if (prefs.visualizationEnabled !== undefined)
visualizationEnabled = prefs.visualizationEnabled;
if (prefs.transitionMode) transitionMode = prefs.transitionMode;
} catch (e) {
console.error("Failed to parse preferences:", e);
}
}
updateUIFromPreferences();
}
/**
* Update UI elements to reflect current preferences
*/
function updateUIFromPreferences() {
// Update waveform button
waveformButtons.forEach((btn) => {
btn.classList.toggle("active", btn.dataset.waveform === currentWaveform);
});
// Update detune toggle button
detuneToggleButtons.forEach((btn) => {
const btnState = btn.dataset.detuneToggle === "on";
btn.classList.toggle("active", btnState === detuneEnabled);
});
// Update detune intensity button
detuneIntensityButtons.forEach((btn) => {
btn.classList.toggle("active", btn.dataset.detune === detuneIntensity);
});
// Update arpeggiator toggle button
arpeggiatorToggleButtons.forEach((btn) => {
const btnState = btn.dataset.arpeggiatorToggle === "on";
btn.classList.toggle("active", btnState === arpeggiatorEnabled);
});
// Update arpeggiator interval button
arpeggiatorIntervalButtons.forEach((btn) => {
const btnInterval = parseInt(btn.dataset.arpeggiatorInterval);
btn.classList.toggle("active", btnInterval === arpeggiatorInterval);
});
// Update visualization toggle button
visualizationToggleButtons.forEach((btn) => {
const btnState = btn.dataset.visualizationToggle === "on";
btn.classList.toggle("active", btnState === visualizationEnabled);
});
// Update transition mode button
transitionButtons.forEach((btn) => {
btn.classList.toggle("active", btn.dataset.transition === transitionMode);
});
updateDetuneDisplay();
detuneIntensityButtons.forEach((b) => (b.disabled = !detuneEnabled));
}
/**
* Save user preferences to localStorage
*/
function saveUserPreferences() {
const prefsKey = "soundswarm_preferences";
const prefs = {
waveform: currentWaveform,
detuneEnabled,
detuneIntensity,
arpeggiatorEnabled,
arpeggiatorInterval,
visualizationEnabled,
transitionMode,
};
localStorage.setItem(prefsKey, JSON.stringify(prefs));
}
/**
* Save session data (debounced)
*/
function saveSession() {
if (saveSessionTimeout) clearTimeout(saveSessionTimeout);
saveSessionTimeout = setTimeout(() => {
const key = `soundswarm_${sessionId}`;
const data = { usedNotes: Array.from(usedNotes) };
localStorage.setItem(key, JSON.stringify(data));
saveSessionTimeout = null;
}, 500);
}
// ============================================
// Note Assignment
// ============================================
/**
* Request a note assignment from the backend or assign locally
*/
async function requestNote() {
statusMessage.textContent = "Requesting your note…";
try {
const response = await fetch("/api/get-note", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
chord: chordNotes,
usedNotes: Array.from(usedNotes),
}),
});
if (response.ok) {
const data = await response.json();
assignNote(data.note);
statusMessage.textContent = "";
} else {
throw new Error("Backend unavailable");
}
} catch (e) {
console.log("Backend unavailable, using local assignment");
const note = assignComplementaryNote(chordNotes, Array.from(usedNotes));
assignNote(note);
statusMessage.textContent = "Offline mode – notes distributed locally";
}
}
/**
* Assign a note to the current user
*/
function assignNote(note) {
currentNote = note;
usedNotes.add(note);
saveSession();
noteDisplay.textContent = note;
noteLabel.textContent = "Tap to play your note";
playButton.textContent = "Play";
playButton.disabled = false;
}
/**
* Assign a complementary note based on music theory
*/
function assignComplementaryNote(chord, used) {
if (used.length >= chord.length) {
usedNotes.clear();
saveSession();
return chord[0];
}
if (used.length === 0) {
return chord[Math.floor(Math.random() * chord.length)];
}
const usedSet = new Set(used);
const usedFreqs = used.map((n) => NOTE_FREQUENCIES[n]).filter((f) => f);
const minUsed = Math.min(...usedFreqs);
const maxUsed = Math.max(...usedFreqs);
const consonance = [1, 1.125, 1.2, 1.25, 1.333, 1.5, 1.667, 1.875, 2];
let bestNote = chord[0];
let bestScore = -Infinity;
for (let i = 0; i < chord.length; i++) {
const note = chord[i];
let score = 0;
const freq = NOTE_FREQUENCIES[note];
if (i === 0) score += 10;
if (i === 2) score += 5;
if (freq < minUsed || freq > maxUsed) score += 8;
for (const usedFreq of usedFreqs) {
const ratio = freq / usedFreq;
let minDiff = Math.abs(consonance[0] - ratio);
for (let j = 1; j < consonance.length; j++) {
const diff = Math.abs(consonance[j] - ratio);
if (diff < minDiff) minDiff = diff;
}
if (minDiff < 0.05) score += 3;
}
if (usedSet.has(note)) score -= 15;
if (score > bestScore) {
bestScore = score;
bestNote = note;
}
}
return bestNote;
}
/**
* Shuffle to a new random note
*/
function shuffleNote() {
const availableNotes = chordNotes.filter((note) => note !== currentNote);
let newNote;
if (availableNotes.length === 0) {
newNote = chordNotes[Math.floor(Math.random() * chordNotes.length)];
} else {
newNote = availableNotes[Math.floor(Math.random() * availableNotes.length)];
}
usedNotes.add(newNote);
saveSession();
if (isPlaying && !isTransitioning) {
if (transitionMode === "glide") {
glideToNote(newNote);
} else {
crossfadeToNote(newNote);
}
} else if (!isPlaying) {
currentNote = newNote;
currentFrequency = NOTE_FREQUENCIES[newNote];
noteDisplay.textContent = newNote;
}
}
// ============================================
// Audio Engine
// ============================================
/**
* Safely ramp a gain parameter using exponential ramp
*/
function safeGainRamp(gainParam, targetValue, duration, startTime = null) {
const now = startTime || audioContext.currentTime;
const safeTarget = targetValue <= 0 ? AUDIO_CONFIG.NEAR_ZERO : targetValue;
const safeDuration = Math.max(duration, AUDIO_CONFIG.MIN_RAMP_TIME);
gainParam.cancelScheduledValues(now);
gainParam.setValueAtTime(
Math.max(gainParam.value, AUDIO_CONFIG.NEAR_ZERO),
now,
);
gainParam.exponentialRampToValueAtTime(safeTarget, now + safeDuration);
}
/**
* Glide smoothly to a new note (frequency change only)
*/
async function glideToNote(newNote) {
if (!isPlaying || !oscillators.length) return;
if (!audioContext || audioContext.state !== "running") return;
const newFrequency = NOTE_FREQUENCIES[newNote];
if (!newFrequency) return;
const now = audioContext.currentTime;
const glideDuration = AUDIO_CONFIG.GLIDE_DURATION;
const detuneValues = detuneEnabled ? DETUNE_PRESETS[detuneIntensity] : [0];
oscillators.forEach(({ osc }, index) => {
const detuneCents = detuneValues[index] || 0;
const targetFreq = newFrequency * Math.pow(2, detuneCents / 1200);
osc.frequency.cancelScheduledValues(now);
osc.frequency.setValueAtTime(osc.frequency.value, now);
osc.frequency.exponentialRampToValueAtTime(targetFreq, now + glideDuration);
});
currentFrequency = newFrequency;
currentNote = newNote;
noteDisplay.textContent = newNote;
}
/**
* Crossfade to a new note (full sound chain replacement)
*/
async function crossfadeToNote(newNote) {
if (!isPlaying || isTransitioning) return;
if (!audioContext || audioContext.state !== "running") {
try {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
if (audioContext.state === "suspended") {
await audioContext.resume();
}
} catch (e) {
console.error("Crossfade: AudioContext not available");
return;
}
}
isTransitioning = true;
const now = audioContext.currentTime;
const crossfadeDuration = AUDIO_CONFIG.CROSSFADE_DURATION;
const oldGainNode = gainNode;
const oldOscillators = oscillators;
const oldLfos = lfos;
const oldFilterNode = filterNode;
const oldDelayNode = delayNode;
const oldDelayFeedbackGain = delayFeedbackGain;
const oldDryGain = dryGain;
const oldWetGain = wetGain;
if (oldGainNode) {
safeGainRamp(oldGainNode.gain, 0, crossfadeDuration, now);
}
if (oldWetGain) {
safeGainRamp(oldWetGain.gain, 0, crossfadeDuration * 0.5, now);
}
currentNote = newNote;
currentFrequency = NOTE_FREQUENCIES[newNote];
noteDisplay.textContent = newNote;
createNewSoundChain();
setTimeout(
() => {
cleanupAudioNodes(
oldOscillators,
oldLfos,
oldGainNode,
oldFilterNode,
oldDelayNode,
oldDelayFeedbackGain,
oldDryGain,
oldWetGain,
);
isTransitioning = false;
},
crossfadeDuration * 1000 + 100,
);
}
/**
* Clean up audio nodes safely
*/
function cleanupAudioNodes(
oscs,
lfoList,
gain,
filter,
delay,
delayFb,
dry,
wet,
) {
if (oscs) {
oscs.forEach(({ osc, pitchLfo }) => {
try {
osc.stop();
pitchLfo.stop();
osc.disconnect();
pitchLfo.disconnect();
} catch (e) {}
});
}
if (lfoList) {
lfoList.forEach((lfo) => {
try {
lfo.stop();
lfo.disconnect();
} catch (e) {}
});
}
[gain, filter, delay, delayFb, dry, wet].forEach((node) => {
if (node) {
try {
node.disconnect();
} catch (e) {}
}
});
}
/**
* Create a new sound chain
*/
function createNewSoundChain() {
const now = audioContext.currentTime;
const newGainNode = audioContext.createGain();
newGainNode.gain.setValueAtTime(AUDIO_CONFIG.NEAR_ZERO, now);
newGainNode.gain.exponentialRampToValueAtTime(
0.3,
now + AUDIO_CONFIG.FADE_IN_DURATION,
);
const newFilterNode = audioContext.createBiquadFilter();
newFilterNode.type = "lowpass";
newFilterNode.frequency.value = 2000;
newFilterNode.Q.value = 1;
let newDelayNode = null;
let newDelayFeedbackGain = null;
let newDryGain = null;
let newWetGain = null;
if (delayEnabled) {
newDelayNode = audioContext.createDelay(5.0);
newDelayNode.delayTime.value = 0.15;
newDelayFeedbackGain = audioContext.createGain();
newDelayFeedbackGain.gain.value = isMobileDevice ? 0.15 : 0.4;
newDryGain = audioContext.createGain();
newWetGain = audioContext.createGain();
newDryGain.gain.value = 0.8;
newWetGain.gain.value = isMobileDevice ? 0.08 : 0.2;
newFilterNode.connect(newDryGain);
newDryGain.connect(audioContext.destination);
newFilterNode.connect(newDelayNode);
newDelayNode.connect(newWetGain);
newWetGain.connect(audioContext.destination);
newDelayNode.connect(newDelayFeedbackGain);
newDelayFeedbackGain.connect(newDelayNode);
} else {
newFilterNode.connect(audioContext.destination);
}
newGainNode.connect(newFilterNode);
const detuneValues = detuneEnabled ? DETUNE_PRESETS[detuneIntensity] : [0];
const numVoices = detuneValues.length;
const newOscillators = [];
const newLfos = [];
const amplitudeLfoFreq = 0.35 * (0.85 + Math.random() * 0.3);
const filterLfoFreq = 0.25 * (0.85 + Math.random() * 0.3);
detuneValues.forEach((detune) => {
const osc = audioContext.createOscillator();
osc.type = currentWaveform;
const detuneMultiplier = Math.pow(2, detune / 1200);
osc.frequency.value = currentFrequency * detuneMultiplier;
const oscGain = audioContext.createGain();
oscGain.gain.setValueAtTime(AUDIO_CONFIG.NEAR_ZERO, now);
oscGain.gain.exponentialRampToValueAtTime(
1 / numVoices,
now + AUDIO_CONFIG.OSC_ATTACK,
);
const pitchLfo = audioContext.createOscillator();
pitchLfo.frequency.value = 0.1;
const pitchLfoGainNode = audioContext.createGain();
pitchLfoGainNode.gain.value = 2;
pitchLfo.connect(pitchLfoGainNode);
pitchLfoGainNode.connect(osc.frequency);
osc.connect(oscGain);
oscGain.connect(newGainNode);
osc.start(now);
pitchLfo.start(now);
newOscillators.push({ osc, oscGain, pitchLfo, pitchLfoGainNode, detune });
});
const volumeLfo = audioContext.createOscillator();
volumeLfo.frequency.value = amplitudeLfoFreq;
const newVolumeLfoGain = audioContext.createGain();
newVolumeLfoGain.gain.value = 0.15;
volumeLfo.connect(newVolumeLfoGain);
newVolumeLfoGain.connect(newGainNode.gain);
volumeLfo.start(now);
newLfos.push(volumeLfo);
volumeLfoStartTime = now;
volumeLfoFrequency = amplitudeLfoFreq;
const filterLfo = audioContext.createOscillator();
filterLfo.frequency.value = filterLfoFreq;
const newFilterLfoGain = audioContext.createGain();
newFilterLfoGain.gain.value = 1500;
filterLfo.connect(newFilterLfoGain);
newFilterLfoGain.connect(newFilterNode.frequency);
filterLfo.start(now);
newLfos.push(filterLfo);
oscillators = newOscillators;
lfos = newLfos;
gainNode = newGainNode;
filterNode = newFilterNode;
delayNode = newDelayNode;
delayFeedbackGain = newDelayFeedbackGain;
dryGain = newDryGain;
wetGain = newWetGain;
volumeLfoGain = newVolumeLfoGain;
filterLfoGain = newFilterLfoGain;
}
/**