-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
1832 lines (1568 loc) · 71.4 KB
/
script.js
File metadata and controls
1832 lines (1568 loc) · 71.4 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
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set canvas size to fill viewport while maintaining circle
function setCanvasSize() {
const size = Math.min(window.innerWidth * 0.85, window.innerHeight * 0.85);
canvas.width = size;
canvas.height = size;
return size;
}
let size = setCanvasSize();
let centerX = size / 2;
let centerY = size / 2;
let maxRadius = size / 2 - 10;
// Musical notes in chromatic scale
const notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const octaves = 4; // Number of octaves (rings) - octaves 3-6, center empty
let hoveredNote = null;
let hoveredOctave = null;
let highlightedSegments = []; // Changed to track specific segments
// Audio context for sound generation
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioCtx = null;
// Note to frequency mapping (A4 = 440Hz standard tuning)
function noteToFrequency(note, octave) {
const noteIndex = notes.indexOf(note);
const a4 = 440; // A4 = 440 Hz (concert pitch)
// A is at index 9 in our notes array
// Calculate semitones from A4
const halfSteps = noteIndex - 9 + (octave - 4) * 12;
return a4 * Math.pow(2, halfSteps / 12);
}
// Color mapping - chromatic circle of fifths inspired
function noteToHue(noteIndex) {
// Map notes to colors in a perceptually pleasing way
const hueMap = {
0: 0, // C - Red
1: 30, // C# - Orange-Red
2: 45, // D - Orange
3: 60, // D# - Yellow-Orange
4: 90, // E - Yellow-Green
5: 120, // F - Green
6: 180, // F# - Cyan
7: 210, // G - Blue-Cyan
8: 240, // G# - Blue
9: 270, // A - Purple
10: 300, // A# - Magenta
11: 330 // B - Pink-Red
};
return hueMap[noteIndex];
}
// Convert HSL to RGB for blending calculations
function hslToRgb(h, s, l) {
h = h / 360;
s = s / 100;
l = l / 100;
const a = s * Math.min(l, 1 - l);
const f = (n, k = (n + h * 12) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
}
// Convert RGB back to HSL
function rgbToHsl(r, g, b) {
r /= 255; g /= 255; b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const diff = max - min;
const sum = max + min;
const l = sum / 2;
if (diff === 0) return [0, 0, Math.round(l * 100)];
const s = l > 0.5 ? diff / (2 - sum) : diff / sum;
let h;
switch (max) {
case r: h = ((g - b) / diff + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / diff + 2) / 6; break;
case b: h = ((r - g) / diff + 4) / 6; break;
}
return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)];
}
// Blend multiple note colors for chord visualization using actual segment colors
function blendChordColors() {
if (highlightedSegments.length === 0) return null;
let totalR = 0, totalG = 0, totalB = 0, totalWeight = 0;
highlightedSegments.forEach(segment => {
const [note, octaveRing] = segment.split('-');
const noteIndex = notes.indexOf(note);
if (noteIndex === -1) return;
// Use same color calculation as the actual wheel segments
const hue = noteToHue(noteIndex);
// Calculate frequency-based brightness (same as drawWheel)
const audioOctave = Number(octaveRing) + 3;
const frequency = noteToFrequency(note, audioOctave);
const minFreq = 130; // C3 (~130Hz) - darkest
const maxFreq = 1047; // C6 (~1047Hz) - brightest
const freqRatio = Math.log(frequency / minFreq) / Math.log(maxFreq / minFreq);
const lightness = 25 + Math.pow(freqRatio, 0.8) * 55; // Match wheel calculation
const saturation = 70; // Match the main wheel saturation
const [r, g, b] = hslToRgb(hue, saturation, lightness);
totalR += r;
totalG += g;
totalB += b;
totalWeight += 1;
});
const avgR = totalR / totalWeight;
const avgG = totalG / totalWeight;
const avgB = totalB / totalWeight;
const [h, s, l] = rgbToHsl(avgR, avgG, avgB);
return { hue: h, saturation: s, lightness: l };
}
// Utility function to convert event coordinates to canvas position
function getCanvasPosition(e) {
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
const rect = canvas.getBoundingClientRect();
const x = (clientX - rect.left) * (canvas.width / rect.width) - centerX;
const y = (clientY - rect.top) * (canvas.height / rect.height) - centerY;
return { x, y };
}
// Utility function to get note data from canvas coordinates
function getNoteFromPosition(x, y) {
const distance = Math.sqrt(x * x + y * y);
let angle = Math.atan2(y, x) + Math.PI / 2;
if (angle < 0) angle += Math.PI * 2;
const centerRadius = maxRadius * 0.2;
if (distance <= maxRadius && distance >= centerRadius) {
const adjustedDistance = distance - centerRadius;
const availableRadius = maxRadius - centerRadius;
const octave = Math.floor(adjustedDistance / (availableRadius / octaves));
const noteIndex = Math.floor((angle / (Math.PI * 2)) * notes.length) % notes.length;
const note = notes[noteIndex];
const audioOctave = octave + 3;
return { note, octave, audioOctave, noteIndex };
}
return null;
}
// Utility function to update display elements
function updateDisplayElements(noteText, noteColor, freqText) {
document.getElementById('noteDisplay').textContent = noteText;
document.getElementById('noteDisplay').style.color = noteColor || '#fff';
document.getElementById('freqDisplay').textContent = freqText;
}
// Extract chord notes from highlighted segments (with repetition for proper weighting)
function getCurrentChordNotes() {
if (highlightedSegments.length === 0) return [];
const chordNotes = [];
highlightedSegments.forEach(segment => {
const [note, octave] = segment.split('-');
chordNotes.push(note);
});
return chordNotes;
}
// Chord recognition database
const chordDatabase = {
// Major triads
'C,E,G': 'C Major',
'C#,F,G#': 'C# Major',
'D,F#,A': 'D Major',
'D#,G,A#': 'D# Major',
'E,G#,B': 'E Major',
'F,A,C': 'F Major',
'F#,A#,C#': 'F# Major',
'G,B,D': 'G Major',
'G#,C,D#': 'G# Major',
'A,C#,E': 'A Major',
'A#,D,F': 'A# Major',
'B,D#,F#': 'B Major',
// Minor triads
'C,D#,G': 'C Minor',
'C#,E,G#': 'C# Minor',
'D,F,A': 'D Minor',
'D#,F#,A#': 'D# Minor',
'E,G,B': 'E Minor',
'F,G#,C': 'F Minor',
'F#,A,C#': 'F# Minor',
'G,A#,D': 'G Minor',
'G#,B,D#': 'G# Minor',
'A,C,E': 'A Minor',
'A#,C#,F': 'A# Minor',
'B,D,F#': 'B Minor',
// Diminished triads
'C,D#,F#': 'C Diminished',
'C#,E,G': 'C# Diminished',
'D,F,G#': 'D Diminished',
'D#,F#,A': 'D# Diminished',
'E,G,A#': 'E Diminished',
'F,G#,B': 'F Diminished',
'F#,A,C': 'F# Diminished',
'G,A#,C#': 'G Diminished',
'G#,B,D': 'G# Diminished',
'A,C,D#': 'A Diminished',
'A#,C#,E': 'A# Diminished',
'B,D,F': 'B Diminished',
// Augmented triads
'C,E,G#': 'C Augmented',
'C#,F,A': 'C# Augmented',
'D,F#,A#': 'D Augmented',
'D#,G,B': 'D# Augmented',
'E,G#,C': 'E Augmented',
'F,A,C#': 'F Augmented',
'F#,A#,D': 'F# Augmented',
'G,B,D#': 'G Augmented',
'G#,C,E': 'G# Augmented',
'A,C#,F': 'A Augmented',
'A#,D,F#': 'A# Augmented',
'B,D#,G': 'B Augmented',
// Seventh chords (dominant 7ths)
'C,E,G,A#': 'C7',
'D,F#,A,C': 'D7',
'E,G#,B,D': 'E7',
'F,A,C,D#': 'F7',
'G,B,D,F': 'G7',
'A,C#,E,G': 'A7',
'B,D#,F#,A': 'B7',
// Major 7ths
'C,E,G,B': 'C Major 7',
'D,F#,A,C#': 'D Major 7',
'E,G#,B,D#': 'E Major 7',
'F,A,C,E': 'F Major 7',
'G,B,D,F#': 'G Major 7',
'A,C#,E,G#': 'A Major 7',
'B,D#,F#,A#': 'B Major 7',
// Minor 7ths
'C,D#,G,A#': 'C Minor 7',
'D,F,A,C': 'D Minor 7',
'E,G,B,D': 'E Minor 7',
'F,G#,C,D#': 'F Minor 7',
'G,A#,D,F': 'G Minor 7',
'A,C,E,G': 'A Minor 7',
'B,D,F#,A': 'B Minor 7',
// Suspended chords
'C,F,G': 'C Suspended 4th',
'C,D,G': 'C Suspended 2nd',
'D,G,A': 'D Suspended 4th',
'D,E,A': 'D Suspended 2nd',
'E,A,B': 'E Suspended 4th',
'E,F#,B': 'E Suspended 2nd',
'F,A#,C': 'F Suspended 4th',
'F,G,C': 'F Suspended 2nd',
'G,C,D': 'G Suspended 4th',
'G,A,D': 'G Suspended 2nd',
'A,D,E': 'A Suspended 4th',
'A,B,E': 'A Suspended 2nd',
'B,E,F#': 'B Suspended 4th',
'B,C#,F#': 'B Suspended 2nd',
// Add 9 chords (major triad + 9th)
'C,D,E,G': 'C Add 9',
'C#,D#,F,G#': 'C# Add 9',
'D,E,F#,A': 'D Add 9',
'D#,F,G,A#': 'D# Add 9',
'E,F#,G#,B': 'E Add 9',
'F,G,A,C': 'F Add 9',
'F#,G#,A#,C#': 'F# Add 9',
'G,A,B,D': 'G Add 9',
'G#,A#,C,D#': 'G# Add 9',
'A,B,C#,E': 'A Add 9',
'A#,C,D,F': 'A# Add 9',
'B,C#,D#,F#': 'B Add 9'
};
// Recognize chord from unique note names
function recognizeChord(uniqueNotes) {
if (uniqueNotes.length < 2) return null;
// Sort notes to normalize chord voicings
const sortedNotes = [...uniqueNotes].sort();
const chordKey = sortedNotes.join(',');
// Check direct match first
if (chordDatabase[chordKey]) {
return chordDatabase[chordKey];
}
// Check for chord inversions by trying different root positions
for (let i = 0; i < sortedNotes.length; i++) {
const rotated = [...sortedNotes.slice(i), ...sortedNotes.slice(0, i)];
const rotatedKey = rotated.join(',');
if (chordDatabase[rotatedKey]) {
return chordDatabase[rotatedKey] + (i > 0 ? ' (inversion)' : '');
}
}
// If no exact match, provide generic description
if (uniqueNotes.length === 2) {
return `${uniqueNotes[0]} + ${uniqueNotes[1]} interval`;
} else if (uniqueNotes.length >= 3) {
return `${uniqueNotes[0]} + ${uniqueNotes.slice(1).join('+')} chord`;
}
return null;
}
function drawWheel() {
ctx.clearRect(0, 0, size, size);
const centerRadius = maxRadius * 0.2; // Center for chord blending
const availableRadius = maxRadius - centerRadius;
const ringWidth = availableRadius / octaves;
for (let octave = 0; octave < octaves; octave++) {
const baseInnerRadius = centerRadius + octave * ringWidth;
const baseOuterRadius = centerRadius + (octave + 1) * ringWidth;
for (let i = 0; i < notes.length; i++) {
const startAngle = (i / notes.length) * Math.PI * 2 - Math.PI / 2;
const endAngle = ((i + 1) / notes.length) * Math.PI * 2 - Math.PI / 2;
// Check if this specific segment is highlighted
const segmentKey = `${notes[i]}-${octave}`;
const isHighlighted = highlightedSegments.includes(segmentKey);
ctx.beginPath();
ctx.arc(centerX, centerY, baseInnerRadius, startAngle, endAngle);
ctx.arc(centerX, centerY, baseOuterRadius, endAngle, startAngle, true);
ctx.closePath();
// Color based on note with frequency-based brightness
const hue = noteToHue(i);
// Calculate actual frequency for this note and octave
// Visual octaves 0-3 map to audio octaves 3-6
const audioOctave = octave + 3;
const frequency = noteToFrequency(notes[i], audioOctave);
// Map frequency to brightness (human hearing range ~20Hz to 20kHz)
// Lower frequencies = darker, higher frequencies = brighter
const minFreq = 130; // C3 (~130Hz) - darkest
const maxFreq = 1047; // C6 (~1047Hz) - brightest
const freqRatio = Math.log(frequency / minFreq) / Math.log(maxFreq / minFreq);
const lightness = 25 + Math.pow(freqRatio, 0.8) * 55; // Gentle curve, 25-80% range
let saturation = 70;
let brightness = lightness;
// Keep natural colors for all states - no color changes for hover or playing
// (Border effects will handle visual feedback)
ctx.fillStyle = `hsl(${hue}, ${saturation}%, ${brightness}%)`;
ctx.fill();
// Border effects for visual feedback
if (isHighlighted) {
// Add prominent border for playing notes
ctx.strokeStyle = `hsl(${hue}, 100%, 90%)`;
ctx.lineWidth = 3;
ctx.stroke();
} else if (hoveredNote === notes[i] && hoveredOctave === octave) {
// Add medium border for hovered notes
ctx.strokeStyle = `hsl(${hue}, 80%, 80%)`;
ctx.lineWidth = 2;
ctx.stroke();
} else {
// Normal subtle border
ctx.strokeStyle = `rgba(255, 255, 255, 0.1)`;
ctx.lineWidth = 0.5;
ctx.stroke();
}
}
}
// Dim non-highlighted segments when something is playing
if (highlightedSegments.length > 0) {
ctx.save();
ctx.globalCompositeOperation = 'multiply';
for (let octave = 0; octave < octaves; octave++) {
const baseInnerRadius = centerRadius + octave * ringWidth;
const baseOuterRadius = centerRadius + (octave + 1) * ringWidth;
for (let i = 0; i < notes.length; i++) {
const segmentKey = `${notes[i]}-${octave}`;
if (!highlightedSegments.includes(segmentKey)) {
const startAngle = (i / notes.length) * Math.PI * 2 - Math.PI / 2;
const endAngle = ((i + 1) / notes.length) * Math.PI * 2 - Math.PI / 2;
ctx.beginPath();
ctx.arc(centerX, centerY, baseInnerRadius, startAngle, endAngle);
ctx.arc(centerX, centerY, baseOuterRadius, endAngle, startAngle, true);
ctx.closePath();
ctx.fillStyle = 'rgba(50, 50, 50, 0.5)';
ctx.fill();
}
}
}
ctx.restore();
}
// Draw chord blending in center circle
if (highlightedSegments.length > 0) {
// Blend chord colors and draw in center
const blendedColor = blendChordColors();
if (blendedColor) {
// Draw the blended chord color as a solid circle
ctx.beginPath();
ctx.arc(centerX, centerY, centerRadius * 0.85, 0, 2 * Math.PI);
ctx.fillStyle = `hsl(${blendedColor.hue}, ${blendedColor.saturation}%, ${blendedColor.lightness}%)`;
ctx.fill();
// Add a subtle border
ctx.strokeStyle = `hsl(${blendedColor.hue}, ${blendedColor.saturation}%, 90%)`;
ctx.lineWidth = 2;
ctx.stroke();
// Add a subtle glow effect
const glowRadius = centerRadius * 1.2;
const gradient = ctx.createRadialGradient(centerX, centerY, centerRadius * 0.85, centerX, centerY, glowRadius);
gradient.addColorStop(0, `hsla(${blendedColor.hue}, ${blendedColor.saturation}%, ${blendedColor.lightness}%, 0)`);
gradient.addColorStop(1, `hsla(${blendedColor.hue}, ${blendedColor.saturation}%, ${Math.min(80, blendedColor.lightness + 20)}%, 0.2)`);
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(centerX, centerY, glowRadius, 0, 2 * Math.PI);
ctx.fill();
}
} else {
// Add subtle center glow when no chord is playing
if (maxRadius > 0) {
const glowRadius = Math.max(10, ringWidth);
const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, glowRadius);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0.1)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
}
}
}
// Tab switching function
function showTab(tabName) {
// Update tab buttons
document.querySelectorAll('.tab-button').forEach(btn => {
btn.classList.remove('active');
});
event.target.classList.add('active');
// Show/hide control groups
document.querySelectorAll('.control-group').forEach(group => {
group.classList.remove('active');
});
document.getElementById(`${tabName}-group`).classList.add('active');
}
// Make showTab globally accessible
window.showTab = showTab;
// Mobile menu functionality
let mobileControlsOpen = false;
let mobileLegendOpen = false;
function toggleMobileControls() {
const controlsBtn = document.getElementById('mobileControlsBtn');
const controls = document.querySelector('.controls');
mobileControlsOpen = !mobileControlsOpen;
if (mobileControlsOpen) {
controlsBtn.classList.add('active');
controls.classList.add('mobile-open');
} else {
controlsBtn.classList.remove('active');
controls.classList.remove('mobile-open');
}
}
function toggleMobileLegend() {
const legendBtn = document.getElementById('mobileLegendBtn');
const legend = document.querySelector('.legend');
mobileLegendOpen = !mobileLegendOpen;
if (mobileLegendOpen) {
legendBtn.classList.add('active');
legend.classList.add('mobile-open');
} else {
legendBtn.classList.remove('active');
legend.classList.remove('mobile-open');
}
}
// Close mobile controls when a control is selected
function closeMobileControlsOnSelection() {
if ((window.innerWidth <= 1024 || window.innerHeight <= 768) && mobileControlsOpen) {
toggleMobileControls();
}
}
// Close menus when tapping outside
function closeMobileMenusOnOutsideClick(e) {
// Don't close if tapping on the mobile buttons themselves
if (e.target.closest('.mobile-controls-btn') || e.target.closest('.mobile-legend-btn')) {
return;
}
// Don't close if tapping inside the panels
if (e.target.closest('.controls') || e.target.closest('.legend')) {
return;
}
// Close both panels if they're open and we're on mobile
if (window.innerWidth <= 1024 || window.innerHeight <= 768) {
if (mobileControlsOpen) {
toggleMobileControls();
}
if (mobileLegendOpen) {
toggleMobileLegend();
}
}
}
// Close menus when tapping outside
function closeMobileMenusOnOutsideClick(e) {
// Don't close if tapping on the mobile buttons themselves
if (e.target.closest('.mobile-controls-btn') || e.target.closest('.mobile-legend-btn')) {
return;
}
// Don't close if tapping inside the panels
if (e.target.closest('.controls') || e.target.closest('.legend')) {
return;
}
// Close both panels if they're open and we're on mobile
if (window.innerWidth <= 1024 || window.innerHeight <= 768) {
if (mobileControlsOpen) {
toggleMobileControls();
}
if (mobileLegendOpen) {
toggleMobileLegend();
}
}
}
// Make functions globally accessible
window.toggleMobileControls = toggleMobileControls;
window.toggleMobileLegend = toggleMobileLegend;
function initAudio() {
if (!audioCtx) {
audioCtx = new AudioContext();
}
}
// Equal loudness compensation based on A-weighting curve
function getEqualLoudnessVolume(frequency, baseVolume = 0.3) {
// Simplified A-weighting approximation for equal loudness
// Peak sensitivity around 1000-4000 Hz, reduced at very low and very high frequencies
const f = frequency;
const f2 = f * f;
const f4 = f2 * f2;
// A-weighting approximation (simplified)
const numerator = 12194 * 12194 * f4;
const denominator = (f2 + 20.6 * 20.6) * Math.sqrt((f2 + 107.7 * 107.7) * (f2 + 737.9 * 737.9)) * (f2 + 12194 * 12194);
const aWeight = numerator / denominator;
// Convert to linear scale and normalize (1000 Hz = reference)
const referenceWeight = 0.5; // Approximation for 1000 Hz
const compensation = Math.min(2.0, Math.max(0.3, referenceWeight / aWeight));
return baseVolume * compensation;
}
function playNote(frequency, duration = 200, volume = 0.3) {
initAudio();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.frequency.value = frequency;
oscillator.type = 'sine';
// Apply equal loudness compensation
const compensatedVolume = getEqualLoudnessVolume(frequency, volume);
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
gainNode.gain.linearRampToValueAtTime(compensatedVolume, audioCtx.currentTime + 0.01);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + duration / 1000);
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + duration / 1000);
return {oscillator, gainNode};
}
// ============================================================================
// REFACTORED: Unified Chord and Scale System (Eliminates 20+ duplicate functions)
// ============================================================================
// Chord definitions - replaces 10+ individual chord functions
const CHORD_DEFINITIONS = {
'major': {
notes: ['C', 'E', 'G'],
name: 'C Major',
description: 'C - E - G (Happy chord)'
},
'minor': {
notes: ['C', 'D#', 'G'],
name: 'C Minor',
description: 'C - E♭ - G (Sad chord)'
},
'diminished': {
notes: ['C', 'D#', 'F#'],
name: 'C Diminished',
description: 'C - E♭ - G♭ (Tense chord)'
},
'augmented': {
notes: ['C', 'E', 'G#'],
name: 'C Augmented',
description: 'C - E - G# (Mysterious chord)'
},
'maj7': {
notes: ['C', 'E', 'G', 'B'],
name: 'C Major 7th',
description: 'C - E - G - B (Jazzy chord)'
},
'min7': {
notes: ['C', 'D#', 'G', 'A#'],
name: 'C Minor 7th',
description: 'C - E♭ - G - B♭ (Smooth chord)'
},
'dom7': {
notes: ['C', 'E', 'G', 'A#'],
name: 'C Dominant 7th',
description: 'C - E - G - B♭ (Bluesy chord)'
},
'sus2': {
notes: ['C', 'D', 'G'],
name: 'C Suspended 2nd',
description: 'C - D - G (Floating chord)'
},
'sus4': {
notes: ['C', 'F', 'G'],
name: 'C Suspended 4th',
description: 'C - F - G (Unresolved chord)'
},
'add9': {
notes: ['C', 'E', 'G', 'D'],
name: 'C Add 9',
description: 'C - E - G - D (Colorful chord)'
}
};
// Scale definitions - replaces 8+ individual scale functions
const SCALE_DEFINITIONS = {
'chromatic': {
notes: ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'],
name: 'Chromatic Scale',
description: 'All 12 semitones'
},
'major': {
notes: ['C', 'D', 'E', 'F', 'G', 'A', 'B'],
name: 'C Major Scale',
description: 'Do-Re-Mi-Fa-Sol-La-Ti (Happy scale)'
},
'minor': {
notes: ['C', 'D', 'D#', 'F', 'G', 'G#', 'A#'],
name: 'C Minor Scale',
description: 'Natural minor (Sad scale)'
},
'pentatonic': {
notes: ['C', 'D', 'E', 'G', 'A'],
name: 'C Pentatonic Scale',
description: '5-note scale (Universal scale)'
},
'harmonic': {
notes: ['C', 'D', 'D#', 'F', 'G', 'G#', 'B'],
name: 'C Harmonic Minor',
description: 'Exotic scale with augmented 2nd'
},
'chromatic_desc': {
notes: ['C', 'B', 'A#', 'A', 'G#', 'G', 'F#', 'F', 'E', 'D#', 'D', 'C#'],
name: 'Chromatic Descending',
description: 'All 12 semitones descending'
},
'blues': {
notes: ['C', 'D#', 'F', 'F#', 'G', 'A#'],
name: 'C Blues Scale',
description: 'Minor pentatonic + blue note'
},
'wholetone': {
notes: ['C', 'D', 'E', 'F#', 'G#', 'A#'],
name: 'C Whole Tone Scale',
description: 'Dreamy impressionist scale'
}
};
// Unified chord player - replaces 10+ duplicate functions
function playChordType(chordType) {
initAudio();
const chord = CHORD_DEFINITIONS[chordType];
if (!chord) {
console.error(`Unknown chord type: ${chordType}`);
return;
}
const chordNotes = chord.notes;
const chordOctave = 1; // Ring 1 = Octave 4
// Visual feedback
highlightedSegments = chordNotes.map(note => `${note}-${chordOctave}`);
drawWheel();
// UI updates with chord recognition taking precedence
const recognizedChord = recognizeChord(chordNotes);
if (recognizedChord) {
document.getElementById('noteDisplay').textContent = recognizedChord;
document.getElementById('freqDisplay').textContent = `${chord.name} - ${chord.description}`;
} else {
document.getElementById('noteDisplay').textContent = chord.name;
document.getElementById('freqDisplay').textContent = chord.description;
}
// Play chord
chordNotes.forEach(note => {
const freq = noteToFrequency(note, 4);
playNote(freq, 1500, 0.2);
});
// Reset UI
setTimeout(() => {
highlightedSegments = [];
drawWheel();
document.getElementById('noteDisplay').textContent = 'Click to hear notes';
document.getElementById('noteDisplay').style.color = '#fff';
document.getElementById('freqDisplay').textContent = 'Hover over the wheel';
}, 1500);
}
// Unified scale player - replaces 8+ duplicate functions
function playScaleType(scaleType) {
initAudio();
const scale = SCALE_DEFINITIONS[scaleType];
if (!scale) {
console.error(`Unknown scale type: ${scaleType}`);
return;
}
const scaleNotes = scale.notes;
let delay = 0;
const noteDelay = 200;
// UI update
document.getElementById('noteDisplay').textContent = `Starting ${scale.name}`;
document.getElementById('freqDisplay').textContent = scale.description;
// Play scale sequence
scaleNotes.forEach((note, index) => {
setTimeout(() => {
const freq = noteToFrequency(note, 4);
playNote(freq, 300);
// Visual feedback for current note - octave 4 maps to ring 1
highlightedSegments = [`${note}-1`]; // Ring 1 = Octave 4
drawWheel();
// Keep highlight active during sequence (don't clear between notes)
// Reset UI after last note
if (index === scaleNotes.length - 1) {
setTimeout(() => {
highlightedSegments = [];
drawWheel();
document.getElementById('noteDisplay').textContent = 'Click to hear notes';
document.getElementById('noteDisplay').style.color = '#fff';
document.getElementById('freqDisplay').textContent = 'Hover over the wheel';
}, 300);
}
}, delay);
delay += noteDelay;
});
}
// ============================================================================
// Melody Functions (kept separate as they have unique chord progressions)
// ============================================================================
function playTwinkleTwinkle() {
initAudio();
// Twinkle, Twinkle, Little Star: C-C-G-G-A-A-G-F-F-E-E-D-D-C
const melody = [
{note: 'C', octave: 4, duration: 400},
{note: 'C', octave: 4, duration: 400},
{note: 'G', octave: 4, duration: 400},
{note: 'G', octave: 4, duration: 400},
{note: 'A', octave: 4, duration: 400},
{note: 'A', octave: 4, duration: 400},
{note: 'G', octave: 4, duration: 800},
{note: 'F', octave: 4, duration: 400},
{note: 'F', octave: 4, duration: 400},
{note: 'E', octave: 4, duration: 400},
{note: 'E', octave: 4, duration: 400},
{note: 'D', octave: 4, duration: 400},
{note: 'D', octave: 4, duration: 400},
{note: 'C', octave: 4, duration: 800}
];
// Classic I-V-vi-IV progression in C major
const chords = [
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major (V)
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major
{notes: ['A', 'C', 'E'], octave: 3, duration: 400}, // A minor (vi)
{notes: ['A', 'C', 'E'], octave: 3, duration: 400}, // A minor
{notes: ['G', 'B', 'D'], octave: 3, duration: 800}, // G major
{notes: ['F', 'A', 'C'], octave: 3, duration: 400}, // F major (IV)
{notes: ['F', 'A', 'C'], octave: 3, duration: 400}, // F major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major (I)
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major (V)
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major
{notes: ['C', 'E', 'G'], octave: 3, duration: 800} // C major (I)
];
playMelodyWithChords(melody, chords, 'Twinkle, Twinkle, Little Star');
}
function playMaryLittleLamb() {
initAudio();
// Mary Had a Little Lamb: E-D-C-D-E-E-E-D-D-D-E-G-G
const melody = [
{note: 'E', octave: 4, duration: 400},
{note: 'D', octave: 4, duration: 400},
{note: 'C', octave: 4, duration: 400},
{note: 'D', octave: 4, duration: 400},
{note: 'E', octave: 4, duration: 400},
{note: 'E', octave: 4, duration: 400},
{note: 'E', octave: 4, duration: 800},
{note: 'D', octave: 4, duration: 400},
{note: 'D', octave: 4, duration: 400},
{note: 'D', octave: 4, duration: 800},
{note: 'E', octave: 4, duration: 400},
{note: 'G', octave: 4, duration: 400},
{note: 'G', octave: 4, duration: 800}
];
// Simple I-V progression in C major
const chords = [
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 800}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 400}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 800}, // G major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 400}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 800} // C major
];
playMelodyWithChords(melody, chords, 'Mary Had a Little Lamb');
}
function playHappyBirthday() {
initAudio();
// Happy Birthday: D-D-E-D-G-F#-D-D-E-D-A-G-D-D-D-B-G-F#-E-C-C-B-G-A-G
const melody = [
{note: 'D', octave: 4, duration: 200},
{note: 'D', octave: 4, duration: 300},
{note: 'E', octave: 4, duration: 500},
{note: 'D', octave: 4, duration: 500},
{note: 'G', octave: 4, duration: 500},
{note: 'F#', octave: 4, duration: 1000},
{note: 'D', octave: 4, duration: 200},
{note: 'D', octave: 4, duration: 300},
{note: 'E', octave: 4, duration: 500},
{note: 'D', octave: 4, duration: 500},
{note: 'A', octave: 4, duration: 500},
{note: 'G', octave: 4, duration: 1000},
{note: 'D', octave: 4, duration: 200},
{note: 'D', octave: 4, duration: 300},
{note: 'D', octave: 5, duration: 500},
{note: 'B', octave: 4, duration: 500},
{note: 'G', octave: 4, duration: 500},
{note: 'F#', octave: 4, duration: 500},
{note: 'E', octave: 4, duration: 1000},
{note: 'C', octave: 5, duration: 200},
{note: 'C', octave: 5, duration: 300},
{note: 'B', octave: 4, duration: 500},
{note: 'G', octave: 4, duration: 500},
{note: 'A', octave: 4, duration: 500},
{note: 'G', octave: 4, duration: 1000}
];
// Classic phrase-based harmony for Happy Birthday
const chords = [
{notes: ['G', 'B', 'D'], octave: 3, duration: 200}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 300}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 500}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 500}, // G major
{notes: ['C', 'E', 'G'], octave: 3, duration: 500}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 1000}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 200}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 300}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 500}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 500}, // G major
{notes: ['D', 'F#', 'A'], octave: 3, duration: 500}, // D major
{notes: ['G', 'B', 'D'], octave: 3, duration: 1000}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 200}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 300}, // G major
{notes: ['G', 'B', 'D'], octave: 3, duration: 500}, // G major
{notes: ['E', 'G', 'B'], octave: 3, duration: 500}, // E minor
{notes: ['C', 'E', 'G'], octave: 3, duration: 500}, // C major
{notes: ['G', 'B', 'D'], octave: 3, duration: 500}, // G major
{notes: ['C', 'E', 'G'], octave: 3, duration: 1000}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 200}, // C major
{notes: ['C', 'E', 'G'], octave: 3, duration: 300}, // C major
{notes: ['E', 'G', 'B'], octave: 3, duration: 500}, // E minor
{notes: ['C', 'E', 'G'], octave: 3, duration: 500}, // C major
{notes: ['D', 'F#', 'A'], octave: 3, duration: 500}, // D major
{notes: ['G', 'B', 'D'], octave: 3, duration: 1000} // G major
];
playMelodyWithChords(melody, chords, 'Happy Birthday');
}
function playAmazingGrace() {
initAudio();
// Amazing Grace complete first verse: "Amazing grace, how sweet the sound, that saved a wretch like me"
const melody = [
// "A-ma-zing grace"
{note: 'G', octave: 3, duration: 400}, // A-
{note: 'C', octave: 4, duration: 600}, // ma-
{note: 'E', octave: 4, duration: 400}, // zing
{note: 'C', octave: 4, duration: 400}, // grace
// "how sweet the sound"
{note: 'E', octave: 4, duration: 400}, // how
{note: 'D', octave: 4, duration: 300}, // sweet
{note: 'C', octave: 4, duration: 900}, // the
{note: 'A', octave: 3, duration: 400}, // sound
{note: 'G', octave: 3, duration: 800}, // (pause)
// "that saved a wretch"
{note: 'G', octave: 3, duration: 400}, // that
{note: 'C', octave: 4, duration: 600}, // saved
{note: 'E', octave: 4, duration: 400}, // a
{note: 'C', octave: 4, duration: 400}, // wretch
// "like me"
{note: 'E', octave: 4, duration: 400}, // like
{note: 'D', octave: 4, duration: 300}, // me
{note: 'C', octave: 4, duration: 1200}, // (hold)
// Second phrase: "I once was lost, but now am found"
{note: 'A', octave: 3, duration: 400}, // I
{note: 'A', octave: 3, duration: 400}, // once
{note: 'G', octave: 3, duration: 400}, // was
{note: 'C', octave: 4, duration: 600}, // lost