forked from sugarlabs/musicblocks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsynthutils.js
More file actions
3516 lines (3225 loc) · 142 KB
/
synthutils.js
File metadata and controls
3516 lines (3225 loc) · 142 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
// Copyright (c) 2016-21 Walter Bender
// Copyright (c) 2025 Anvita Prasad DMP'25
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
/*
global
_, last, Tone, require, getTemperament, pitchToNumber,
getNoteFromInterval, FLAT, SHARP, pitchToFrequency, getCustomNote,
getOctaveRatio, isCustomTemperament, Singer, DOUBLEFLAT, DOUBLESHARP,
DEFAULTDRUM, getOscillatorTypes, numberToPitch, platform,
getArticulation, piemenuPitches, docById, slicePath, wheelnav, platformColor,
DEFAULTVOICE
*/
/*
Global Locations
- js/utils/utils.js
_, last, docById
- js/utils/musicutils.js
pitchToNumber, getNoteFromInterval, FLAT, SHARP, pitchToFrequency, getCustomNote,
isCustomTemperament, DOUBLEFLAT, DOUBLESHARP, DEFAULTDRUM, getOscillatorTypes, numberToPitch,
getArticulation, getOctaveRatio, getTemperament, DEFAULTVOICE
- js/turtle-singer.js
Singer
- js/utils/platformstyle.js
platform, platformColor
- js/piemenus.js
piemenuPitches
- js/utils/wheelnav.js
wheelnav, slicePath
*/
/*
exported
NOISENAMES, VOICENAMES, DRUMNAMES, EFFECTSNAMES, CUSTOMSAMPLES,
instrumentsEffects, instrumentsFilters, Synth
*/
/**
* The number of voices in polyphony.
* @constant
* @type {number}
* @default 3
*/
const POLYCOUNT = 3;
/**
* Array of names and details for various noise synthesizers.
* @constant
* @type {Array<Array<string>>}
*/
const NOISENAMES = [
//.TRANS: white noise synthesizer
[_("white noise"), "noise1", "images/synth.svg", "electronic"],
//.TRANS: brown noise synthesizer
[_("brown noise"), "noise2", "images/synth.svg", "electronic"],
//.TRANS: pink noise synthesizer
[_("pink noise"), "noise3", "images/synth.svg", "electronic"]
];
/**
* Array of names and details for various musical instruments.
* @constant
* @type {Array<Array<string>>}
*/
const VOICENAMES = [
//.TRANS: musical instrument
[_("piano"), "piano", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("violin"), "violin", "images/voices.svg", "string"],
//.TRANS: viola musical instrument
[_("viola"), "viola", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("cello"), "cello", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("bass"), "bass", "images/voices.svg", "string"],
//.TRANS: viola musical instrument
[_("double bass"), "double bass", "images/voices.svg", "string"],
//.TRANS: sitar musical instrument
[_("sitar"), "sitar", "images/synth.svg", "string"],
//.TRANS: harmonium musical instrument
[_("harmonium"), "harmonium", "images/voices.svg", "string"],
//.TRANS: mandolin musical instrument
[_("mandolin"), "mandolin", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("guitar"), "guitar", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("acoustic guitar"), "acoustic guitar", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("flute"), "flute", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("clarinet"), "clarinet", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("saxophone"), "saxophone", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("tuba"), "tuba", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("trumpet"), "trumpet", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("oboe"), "oboe", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("trombone"), "trombone", "images/voices.svg", "wind"],
//.TRANS: musical instrument
[_("banjo"), "banjo", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("koto"), "koto", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("dulcimer"), "dulcimer", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("electric guitar"), "electric guitar", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("bassoon"), "bassoon", "images/voices.svg", "string"],
//.TRANS: musical instrument
[_("celeste"), "celeste", "images/voices.svg", "string"],
//.TRANS: xylophone musical instrument
[_("xylophone"), "xylophone", "images/8_bellset_key_6.svg", "precussion"],
//.TRANS: polytone synthesizer
[_("electronic synth"), "electronic synth", "images/synth.svg", "electronic"],
//.TRANS: simple monotone synthesizer
// [_('simple 1'), 'simple 1', 'images/synth.svg', 'electronic'],
//.TRANS: simple monotone synthesizer
// [_('simple-2'), 'simple 2', 'images/synth.svg', 'electronic'],
//.TRANS: simple monotone synthesizer
// [_('simple-3'), 'simple 3', 'images/synth.svg', 'electronic'],
//.TRANS: simple monotone synthesizer
// [_('simple-4'), 'simple 4', 'images/synth.svg', 'electronic'],
//.TRANS: sine wave
[_("sine"), "sine", "images/synth.svg", "electronic"],
//.TRANS: square wave
[_("square"), "square", "images/synth.svg", "electronic"],
//.TRANS: sawtooth wave
[_("sawtooth"), "sawtooth", "images/synth.svg", "electronic"],
//.TRANS: triangle wave
[_("triangle"), "triangle", "images/synth.svg", "electronic"],
//.TRANS: customize voice
[_("custom"), "custom", "images/synth.svg", "electronic"],
//.TRANS: vibraphone musical instrument
[_("vibraphone"), "vibraphone", "images/synth.svg", "electronic"]
];
// drum symbols are from
// http://lilypond.org/doc/v2.18/Documentation/notation/percussion-notes
/**
* Array of names and details for various drum instruments.
* @constant
* @type {Array<Array<string>>}
*/
const DRUMNAMES = [
//.TRANS: musical instrument
[_("snare drum"), "snare drum", "images/snaredrum.svg", "sn", "drum"],
//.TRANS: musical instrument
[_("kick drum"), "kick drum", "images/kick.svg", "hh", "drum"],
//.TRANS: musical instrument
[_("tom tom"), "tom tom", "images/tom.svg", "tomml", "drum"],
//.TRANS: musical instrument
[_("floor tom"), "floor tom", "images/floortom.svg", "tomfl", "drum"],
//.TRANS: musical instrument
[_("bass drum"), "bass drum", "images/kick.svg", "tomfl", "drum"],
//.TRANS: a drum made from an inverted cup
[_("cup drum"), "cup drum", "images/cup.svg", "hh", "drum"],
//.TRANS: musical instrument
[_("darbuka drum"), "darbuka drum", "images/darbuka.svg", "hh", "drum"],
//.TRANS: musical instrument
[_("taiko"), "japanese drum", "images/tom.svg", "hh", "drum"],
//.TRANS: musical instrument
[_("hi hat"), "hi hat", "images/hihat.svg", "hh", "bell"],
//.TRANS: a small metal bell
[_("ride bell"), "ride bell", "images/ridebell.svg", "rb", "bell"],
//.TRANS: musical instrument
[_("cow bell"), "cow bell", "images/cowbell.svg", "cb", "bell"],
//.TRANS: musical instrument
[_("triangle bell"), "triangle bell", "images/trianglebell.svg", "tri", "bell"],
//.TRANS: musical instrument
[_("finger cymbals"), "finger cymbals", "images/fingercymbals.svg", "cymca", "bell"],
//.TRANS: musical instrument
// [_('japanese bell'), 'japanese bell', 'images/cowbell.svg', 'hh', 'bell'],
//.TRANS: a musically tuned set of bells
[_("chime"), "chime", "images/chime.svg", "cymca", "bell"],
//.TRANS: a musical instrument
[_("gong"), "gong", "images/gong.svg", "cymca", "bell"],
//.TRANS: sound effect
[_("clang"), "clang", "images/clang.svg", "cymca", "effect"],
//.TRANS: sound effect
[_("crash"), "crash", "images/crash.svg", "cymca", "effect"],
//.TRANS: sound effect
[_("bottle"), "bottle", "images/bottle.svg", "hh", "effect"],
//.TRANS: sound effect
[_("clap"), "clap", "images/clap.svg", "hc", "effect"],
//.TRANS: sound effect
[_("slap"), "slap", "images/slap.svg", "vibs", "effect"],
//.TRANS: sound effect
[_("splash"), "splash", "images/splash.svg", "hh", "effect"],
//.TRANS: sound effect
[_("bubbles"), "bubbles", "images/bubbles.svg", "hh", "effect"],
//.TRANS: sound effect
[_("raindrop"), "raindrop", "images/bubbles.svg", "hh", "effect"],
//.TRANS: animal sound effect
[_("cat"), "cat", "images/cat.svg", "hh", "animal"],
//.TRANS: animal sound effect
[_("cricket"), "cricket", "images/cricket.svg", "hh", "animal"],
//.TRANS: animal sound effect
[_("dog"), "dog", "images/dog.svg", "hh", "animal"],
//.TRANS: animal sound effect
[_("duck"), "duck", "images/duck.svg", "hh", "animal"]
];
/**
* Array of names for various sound effect presets.
* @constant
* @type {Array<string>}
*/
const EFFECTSNAMES = ["duck", "dog", "cricket", "cat", "bubbles", "splash", "bottle"];
/**
* Array of file paths for different sound samples.
* @constant
* @type {Array<string>}
*/
/**
* Object containing file paths and global variable names for different sound samples.
* @constant
* @type {Object}
*/
const SAMPLE_INFO = {
voice: {
"piano": { path: "samples/piano", global: "PIANO_SAMPLE" },
"violin": { path: "samples/violin", global: "VIOLIN_SAMPLE" },
"viola": { path: "samples/viola", global: "VIOLA_SAMPLE" },
"double bass": { path: "samples/doublebass", global: "DOUBLEBASS_SAMPLE" },
"cello": { path: "samples/cello", global: "CELLO_SAMPLE" },
"flute": { path: "samples/flute", global: "FLUTE_SAMPLE" },
"clarinet": { path: "samples/clarinet", global: "CLARINET_SAMPLE" },
"saxophone": { path: "samples/saxophone", global: "SAXOPHONE_SAMPLE" },
"trumpet": { path: "samples/trumpet", global: "TRUMPET_SAMPLE" },
"oboe": { path: "samples/oboe", global: "OBOE_SAMPLE" },
"trombone": { path: "samples/trombone", global: "TROMBONE_SAMPLE" },
"tuba": { path: "samples/tuba", global: "TUBA_SAMPLE" },
"guitar": { path: "samples/guitar", global: "GUITAR_SAMPLE" },
"acoustic guitar": { path: "samples/acguit", global: "ACOUSTIC_GUITAR_SAMPLE" },
"bass": { path: "samples/bass", global: "BASS_SAMPLE" },
"banjo": { path: "samples/banjo", global: "BANJO_SAMPLE" },
"koto": { path: "samples/koto", global: "KOTO_SAMPLE" },
"dulcimer": { path: "samples/dulcimer", global: "DULCIMER_SAMPLE" },
"electric guitar": { path: "samples/electricguitar", global: "ELECTRICGUITAR_SAMPLE" },
"bassoon": { path: "samples/bassoon", global: "BASSOON_SAMPLE" },
"celeste": { path: "samples/celeste", global: "CELESTE_SAMPLE" },
"vibraphone": { path: "samples/vibraphone", global: "VIBRAPHONE_SAMPLE" },
"xylophone": { path: "samples/xylophone", global: "XYLOPHONE_SAMPLE" },
"sitar": { path: "samples/sitar", global: "SITAR_SAMPLE" },
"harmonium": { path: "samples/harmonium", global: "HARMONIUM_SAMPLE" },
"mandolin": { path: "samples/mandolin", global: "MANDOLIN_SAMPLE" }
},
drum: {
"bottle": { path: "samples/bottle", global: "BOTTLE_SAMPLE" },
"clap": { path: "samples/clap", global: "CLAP_SAMPLE" },
"darbuka drum": { path: "samples/darbuka", global: "DARBUKA_SAMPLE" },
"hi hat": { path: "samples/hihat", global: "HIHAT_SAMPLE" },
"splash": { path: "samples/splash", global: "SPLASH_SAMPLE" },
"bubbles": { path: "samples/bubbles", global: "BUBBLES_SAMPLE" },
"raindrop": { path: "samples/raindrop", global: "RAINDROP_SAMPLE" },
"cow bell": { path: "samples/cowbell", global: "COWBELL_SAMPLE" },
"dog": { path: "samples/dog", global: "DOG_SAMPLE" },
"kick drum": { path: "samples/kick", global: "KICK_SAMPLE" },
"tom tom": { path: "samples/tom", global: "TOM_SAMPLE" },
"cat": { path: "samples/cat", global: "CAT_SAMPLE" },
"crash": { path: "samples/crash", global: "CRASH_SAMPLE" },
"duck": { path: "samples/duck", global: "DUCK_SAMPLE" },
"ride bell": { path: "samples/ridebell", global: "RIDEBELL_SAMPLE" },
"triangle bell": { path: "samples/triangle", global: "TRIANGLE_SAMPLE" },
"chime": { path: "samples/chime", global: "CHIME_SAMPLE" },
"gong": { path: "samples/gong", global: "GONG_SAMPLE" },
"cricket": { path: "samples/cricket", global: "CRICKET_SAMPLE" },
"finger cymbals": { path: "samples/fingercymbal", global: "FINGERCYMBAL_SAMPLE" },
"slap": { path: "samples/slap", global: "SLAP_SAMPLE" },
"japanese drum": { path: "samples/japanese_drum", global: "JAPANESE_DRUM_SAMPLE" },
"clang": { path: "samples/clang", global: "CLANG_SAMPLE" },
"cup drum": { path: "samples/cup", global: "CUP_SAMPLE" },
"floor tom": { path: "samples/floortom", global: "FLOORTOM_SAMPLE" },
"bass drum": { path: "samples/bassdrum", global: "BASSDRUM_SAMPLE" },
"snare drum": { path: "samples/snare", global: "SNARE_SAMPLE" }
}
};
/**
* Array of file paths for different sound samples.
* @constant
* @type {Array<string>}
*/
const SOUNDSAMPLESDEFINES = Object.values(SAMPLE_INFO.voice)
.map(s => s.path)
.concat(Object.values(SAMPLE_INFO.drum).map(s => s.path));
// Some samples have a default volume other than 50 (See #1697)
/**
* Default volume settings for different synth instruments.
* @constant
* @type {Object.<string, number>}
*/
const DEFAULTSYNTHVOLUME = {
"flute": 90,
"electronic synth": 90,
"piano": 100,
"viola": 20,
"violin": 20,
"banjo": 90,
"koto": 70,
"kick drum": 100,
"tom tom": 100,
"floor tom": 100,
"bass drum": 100,
"cup drum": 100,
"darbuka drum": 100,
"hi hat": 100,
"ride bell": 100,
"cow bell": 100,
"triangle bell": 60,
"finger cymbals": 70,
"chime": 90,
"gong": 70,
"clang": 70,
"crash": 90,
"clap": 90,
"slap": 60,
"vibraphone": 100,
"xylophone": 100,
"japanese drum": 90,
"sitar": 100,
"harmonium": 100,
"mandolin": 100
};
/**
* The sample has a pitch which is subsequently transposed.
* This object defines the starting pitch number for different samples.
* @constant
* @type {Object.<string, [string, number]>}
*/
const SAMPLECENTERNO = {
"piano": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"violin": ["C5", 51], // pitchToNumber('C', 5, 'C Major')],
"cello": ["C3", 27], // pitchToNumber('C', 3, 'C Major')],
"bass": ["C3", 27], // pitchToNumber('C', 2, 'C Major')],
"guitar": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"acoustic guitar": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"flute": ["F#5", 57], // pitchToNumber('F#', 57, 'C Major')],
"saxophone": ["C5", 51], // pitchToNumber('C', 5, 'C Major')],
"clarinet": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"tuba": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"trumpet": ["C3", 27], // pitchToNumber('C', 3, 'C Major')],
"oboe": ["C4", 39], // pitchToNumber('C', 3, 'C Major')],
"trombone": ["C3", 27], // pitchToNumber('C', 3, 'C Major')],
"banjo": ["C6", 63], // pitchToNumber('C', 6, 'C Major')],
"koto": ["C5", 51], // pitchToNumber('C', 5, 'C Major')],
"dulcimer": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"electric guitar": ["C3", 27], // pitchToNumber('C', 3, 'C Major')],
"bassoon": ["D4", 41], // pitchToNumber('D', 4, 'D Major')],
"celeste": ["C3", 27], // pitchToNumber('C', 3, 'C Major')],
"vibraphone": ["C5", 51], // pitchToNumber('C', 5, 'C Major')],
"xylophone": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"viola": ["D4", 53], // pitchToNumber('D', 4, 'D Major')],
"double bass": ["C4", 39], // pitchToNumber('C', 4, 'C Major')],
"sitar": ["C4", 39], // pitchToNumber('C', 4, 'C Major')]
"harmonium": ["C4", 39] // pitchToNumber('C', 4, 'C Major')]
};
/**
* The sample has multiple pitch which is subsequently transposed.
* This object defines the starting pitch for different samples.
* @constant
* @type {Object.<string, Array<string>>}
*/
const MULTIPITCH = {
mandolin: ["A4", "A5", "A6"]
};
/**
* Array to store custom samples.
* @constant
* @type {Array}
*/
const CUSTOMSAMPLES = [];
/**
* Array of percussion instruments.
* @constant
* @type {Array<string>}
*/
const percussionInstruments = ["koto", "banjo", "dulcimer", "xylophone", "celeste"];
/**
* Array of string instruments.
* @constant
* @type {Array<string>}
*/
const stringInstruments = [
"piano",
"harmonium",
"sitar",
"guitar",
"acoustic guitar",
"electric guitar"
];
/**
* Validates and sets parameters for an instrument.
* @function
* @param {Object} defaultParams - The default parameters for the instrument.
* @param {Object} params - The parameters to be set for the instrument.
* @returns {Object} - The validated and set parameters.
*/
const validateAndSetParams = (defaultParams, params) => {
if (defaultParams && defaultParams !== null && params && params !== undefined) {
for (const key in defaultParams) {
if (key in params && params[key] !== undefined) defaultParams[key] = params[key];
}
}
return defaultParams;
};
// This object contains mapping between instrument name and
// corresponding synth object. The instrument name is the one that
// the user sets in the "Timbre" clamp and uses in the "Set Timbre"
// clamp; There is one instrument dictionary per turtle.
/**
* Object containing mapping between turtle ID and instrument dictionaries.
* @type {Object.<number, Object>}
*/
const instruments = { 0: {} };
/**
* Object containing mapping between instrument name and its source.
* @type {Object.<string, [number, string]>}
* e.g. instrumentsSource['kick drum'] = [1, 'kick drum']
*/
const instrumentsSource = {};
/**
* Object containing effects associated with instruments in the timbre widget.
* @type {Object.<number, Object>}
*/
const instrumentsEffects = { 0: {} };
/**
* Object containing filters associated with instruments in the timbre widget.
* @type {Object.<number, Object>}
*/
const instrumentsFilters = { 0: {} };
/**
* Synth constructor function.
* @constructor
*/
function Synth() {
// Isolate synth functions here.
/**
* Built-in synth types.
* @type {Object.<string, number>}
*/
const BUILTIN_SYNTHS = {
"sine": 1,
"triangle": 1,
"sawtooth": 1,
"square": 1,
"pluck": 1,
"noise1": 1,
"noise2": 1,
"noise3": 1,
"poly": 1,
"simple 1": 1,
"simple 2": 1,
"simple 3": 1,
"simple 4": 1,
"custom": 1
};
/**
* Custom synth types.
* @type {Object.<string, number>}
*/
const CUSTOM_SYNTHS = {
amsynth: 1,
fmsynth: 1,
duosynth: 1
};
// Using Tone.js
// this.tone = new Tone();
this.tone = null;
Tone.Buffer.onload = () => {
// eslint-disable-next-line no-console
console.debug("sample loaded");
};
/**
* Object to store samples.
* @type {Object}
*/
this.samples = null;
/**
* Suffix for sample names.
* @type {string}
*/
this.samplesuffix = "_SAMPLE";
/**
* Manifest for sample loading.
* @type {Object}
*/
this.samplesManifest = null;
/**
* Flag to track changes in temperament.
* @type {boolean}
*/
this.changeInTemperament = false;
/**
* Current temperament.
* @type {string}
*/
this.inTemperament = "equal";
/**
* Starting pitch note.
* @type {string}
*/
this.startingPitch = "C4";
/**
* Frequencies of notes in the current temperament.
* @type {Object.<string, [number, number]>}
*/
this.noteFrequencies = {};
/**
* Tuner microphone input.
* @type {Tone.UserMedia|null}
*/
this.tunerMic = null;
/**
* Tuner analyser for pitch detection.
* @type {Tone.Analyser|null}
*/
this.tunerAnalyser = null;
/**
* Pitch detection function.
* @type {function|null}
*/
this.detectPitch = null;
/**
* Function to initialize a new Tone.js instance.
* @function
*/
this.newTone = () => {
this.tone = Tone;
};
/**
* Function to get the current temperament.
* @function
* @returns {string} - The current temperament.
*/
this.whichTemperament = () => {
return this.inTemperament;
};
/**
* Function to handle temperament changes.
* @function
* @param {string} temperament - The new temperament.
* @param {string} startingPitch - The starting pitch note.
*/
this.temperamentChanged = (temperament, startingPitch) => {
let startPitch = startingPitch;
const t = getTemperament(temperament);
const len = startPitch.length;
const number = pitchToNumber(
startPitch.substring(0, len - 1),
startPitch.slice(-1),
"C major"
);
const startPitchObj = numberToPitch(number);
startPitch = (startPitchObj[0] + startPitchObj[1]).toString();
if (startPitch.substring(1, len - 1) === FLAT || startPitch.substring(1, len - 1) === "b") {
startPitch = startPitch.replace(FLAT, "b");
} else if (
startPitch.substring(1, len - 1) === SHARP ||
startPitch.substring(1, len - 1) === "#"
) {
startPitch = startPitch.replace(SHARP, "#");
}
const frequency = Tone.Frequency(startPitch).toFrequency();
// Cache getNoteFromInterval results to avoid duplicate calls (performance optimization)
const intervalCache = {
"minor 2": getNoteFromInterval(startingPitch, "minor 2"),
"augmented 1": getNoteFromInterval(startingPitch, "augmented 1"),
"major 2": getNoteFromInterval(startingPitch, "major 2"),
"minor 3": getNoteFromInterval(startingPitch, "minor 3"),
"augmented 2": getNoteFromInterval(startingPitch, "augmented 2"),
"major 3": getNoteFromInterval(startingPitch, "major 3"),
"augmented 3": getNoteFromInterval(startingPitch, "augmented 3"),
"diminished 4": getNoteFromInterval(startingPitch, "diminished 4"),
"perfect 4": getNoteFromInterval(startingPitch, "perfect 4"),
"augmented 4": getNoteFromInterval(startingPitch, "augmented 4"),
"diminished 5": getNoteFromInterval(startingPitch, "diminished 5"),
"perfect 5": getNoteFromInterval(startingPitch, "perfect 5"),
"augmented 5": getNoteFromInterval(startingPitch, "augmented 5"),
"minor 6": getNoteFromInterval(startingPitch, "minor 6"),
"major 6": getNoteFromInterval(startingPitch, "major 6"),
"augmented 6": getNoteFromInterval(startingPitch, "augmented 6"),
"minor 7": getNoteFromInterval(startingPitch, "minor 7"),
"major 7": getNoteFromInterval(startingPitch, "major 7"),
"augmented 7": getNoteFromInterval(startingPitch, "augmented 7"),
"diminished 8": getNoteFromInterval(startingPitch, "diminished 8"),
"perfect 8": getNoteFromInterval(startingPitch, "perfect 8")
};
this.noteFrequencies = {
// note: [octave, Frequency]
[startingPitch.substring(0, len - 1)]: [Number(startingPitch.slice(-1)), frequency],
[intervalCache["minor 2"][0]]: [intervalCache["minor 2"][1], t["minor 2"] * frequency],
[intervalCache["augmented 1"][0]]: [
intervalCache["augmented 1"][1],
t["augmented 1"] * frequency
],
[intervalCache["major 2"][0]]: [intervalCache["major 2"][1], t["major 2"] * frequency],
[intervalCache["minor 3"][0]]: [intervalCache["minor 3"][1], t["minor 3"] * frequency],
[intervalCache["augmented 2"][0]]: [
intervalCache["augmented 2"][1],
t["augmented 2"] * frequency
],
[intervalCache["major 3"][0]]: [intervalCache["major 3"][1], t["major 3"] * frequency],
[intervalCache["augmented 3"][0]]: [
intervalCache["augmented 3"][1],
t["augmented 3"] * frequency
],
[intervalCache["diminished 4"][0]]: [
intervalCache["diminished 4"][1],
t["diminished 4"] * frequency
],
[intervalCache["perfect 4"][0]]: [
intervalCache["perfect 4"][1],
t["perfect 4"] * frequency
],
[intervalCache["augmented 4"][0]]: [
intervalCache["augmented 4"][1],
t["augmented 4"] * frequency
],
[intervalCache["diminished 5"][0]]: [
intervalCache["diminished 5"][1],
t["diminished 5"] * frequency
],
[intervalCache["perfect 5"][0]]: [
intervalCache["perfect 5"][1],
t["perfect 5"] * frequency
],
[intervalCache["augmented 5"][0]]: [
intervalCache["augmented 5"][1],
t["augmented 5"] * frequency
],
[intervalCache["minor 6"][0]]: [intervalCache["minor 6"][1], t["minor 6"] * frequency],
[intervalCache["major 6"][0]]: [intervalCache["major 6"][1], t["major 6"] * frequency],
[intervalCache["augmented 6"][0]]: [
intervalCache["augmented 6"][1],
t["augmented 6"] * frequency
],
[intervalCache["minor 7"][0]]: [intervalCache["minor 7"][1], t["minor 7"] * frequency],
[intervalCache["major 7"][0]]: [intervalCache["major 7"][1], t["major 7"] * frequency],
[intervalCache["augmented 7"][0]]: [
intervalCache["augmented 7"][1],
t["augmented 7"] * frequency
],
[intervalCache["diminished 8"][0]]: [
intervalCache["diminished 8"][1],
t["diminished 8"] * frequency
],
[intervalCache["perfect 8"][0]]: [
intervalCache["perfect 8"][1],
t["perfect 8"] * frequency
]
};
for (const key in this.noteFrequencies) {
let note;
if (key.substring(1, key.length) === FLAT || key.substring(1, key.length) === "b") {
note = key.substring(0, 1) + "" + "b";
this.noteFrequencies[note] = this.noteFrequencies[key];
// eslint-disable-next-line no-delete-var
delete this.noteFrequencies[key];
} else if (
key.substring(1, key.length) === SHARP ||
key.substring(1, key.length) === "#"
) {
note = key.substring(0, 1) + "" + "#";
this.noteFrequencies[note] = this.noteFrequencies[key];
// eslint-disable-next-line no-delete-var
delete this.noteFrequencies[key];
}
}
this.changeInTemperament = false;
};
/**
* Function to get the frequency of notes.
* @function
* @param {string|number|string[]} notes - The notes to get frequencies for.
* @param {boolean} changeInTemperament - Whether there is a change in temperament.
* @returns {number|number[]} - The frequency or frequencies.
*/
this.getFrequency = (notes, changeInTemperament) => {
return this._getFrequency(notes, changeInTemperament);
};
/**
* Internal function to get the frequency of notes.
* @function
* @param {string|number|string[]} notes - The notes to get frequencies for.
* @param {boolean} changeInTemperament - Whether there is a change in temperament.
* @param {string} temperament - The temperament to use.
* @returns {number|number[]} - The frequency or frequencies.
* @private
*/
this._getFrequency = (notes, changeInTemperament, temperament) => {
if (changeInTemperament) {
if (temperament === undefined) {
this.temperamentChanged(this.inTemperament, this.startingPitch);
} else {
//To get frequencies in Temperament Widget.
this.temperamentChanged(temperament, this.startingPitch);
}
}
if (this.inTemperament === "equal") {
let len, note, octave;
if (typeof notes === "string") {
len = notes.length;
note = notes.substring(0, len - 1);
octave = Number(notes.slice(-1));
return pitchToFrequency(note, octave, 0, "c major");
} else if (typeof notes === "number") {
return notes;
} else {
const results = [];
for (let i = 0; i < notes.length; i++) {
if (typeof notes[i] === "string") {
len = notes[i].length;
note = notes[i].substring(0, len - 1);
octave = Number(notes[i].slice(-1));
results.push(pitchToFrequency(note, octave, 0, "c major"));
} else {
results.push(notes[i]);
}
}
return results;
}
}
const __getFrequency = oneNote => {
const len = oneNote.length;
for (const note in this.noteFrequencies) {
if (note === oneNote.substring(0, len - 1)) {
if (this.noteFrequencies[note][0] === Number(oneNote.slice(-1))) {
//Note to be played is in the same octave.
return this.noteFrequencies[note][1];
} else {
//Note to be played is not in the same octave.
const power = Number(oneNote.slice(-1)) - this.noteFrequencies[note][0];
return this.noteFrequencies[note][1] * Math.pow(2, power);
}
}
}
};
if (typeof notes === "string") {
return __getFrequency(notes);
} else if (typeof notes === "object") {
const results = [];
for (let i = 0; i < notes.length; i++) {
if (typeof notes[i] === "string") {
results.push(__getFrequency(notes[i]));
} else {
// Hertz?
results.push(notes[i]);
}
}
return results;
} else {
// Hertz?
return notes;
}
};
/**
* Function to get custom frequency for notes.
* @function
* @param {string|number|string[]} notes - The notes to get frequencies for.
* @param {string} customID - The custom temperament ID.
* @returns {number|number[]} - The frequency or frequencies.
*/
this.getCustomFrequency = (notes, customID) => {
const __getCustomFrequency = (oneNote, startingPitch) => {
const octave = oneNote.slice(-1);
oneNote = getCustomNote(oneNote.substring(0, oneNote.length - 1));
const pitch = startingPitch;
const startPitchFrequency = pitchToFrequency(
pitch.substring(0, pitch.length - 1),
pitch.slice(-1),
0,
"C Major"
);
if (typeof oneNote !== "number") {
const thisTemperament = getTemperament(customID);
for (const pitchNumber in thisTemperament) {
if (pitchNumber !== "pitchNumber") {
if (
(isCustomTemperament(customID) &&
oneNote === thisTemperament[pitchNumber][3]) ||
oneNote === thisTemperament[pitchNumber][1]
) {
const octaveDiff = octave - thisTemperament[pitchNumber][2];
return Number(
thisTemperament[pitchNumber][0] *
startPitchFrequency *
Math.pow(getOctaveRatio(), octaveDiff)
);
}
}
}
}
return oneNote;
};
if (typeof notes === "string") {
return __getCustomFrequency(notes, this.startingPitch);
} else if (typeof notes === "object") {
const results = [];
for (let i = 0; i < notes.length; i++) {
if (typeof notes[i] === "string") {
results.push(__getCustomFrequency(notes[i], this.startingPitch));
} else {
// Hertz?
results.push(notes[i]);
}
}
return results;
} else {
// Hertz?
return notes;
}
};
/**
* Function to resume the Tone.js context.
* @function
*/
this.resume = () => {
if (this.tone === null) {
this.newTone();
}
this.tone.context.resume();
};
/*eslint-disable no-undef*/
/**
* Function to load samples.
* @function
*/
this.loadSamples = () => {
/*eslint-disable no-prototype-builtins*/
if (this.samples === null) {
this.samples = { voice: {}, drum: {} };
// Pre-populate with null to indicate they exist as valid instruments but are not loaded
for (const type in SAMPLE_INFO) {
for (const name in SAMPLE_INFO[type]) {
this.samples[type][name] = null;
}
}
this.samples.voice["empty"] = () => null;
}
};
/**
* Loads samples into the Synth instance.
* @function
* @memberof Synth
*/
/**
* Loads a specific sample into the Synth instance asynchronously.
* @function
* @memberof Synth
* @param {string} sampleName - The name of the sample to load.
* @returns {Promise<void>} - A promise that resolves when the sample is loaded.
*/
this._loadSample = sampleName => {
return new Promise((resolve, reject) => {
let found = false;
let sampleType = null;
let sampleInfo = null;
// Find the sample info
for (const type in SAMPLE_INFO) {
if (SAMPLE_INFO[type][sampleName]) {
sampleType = type;
sampleInfo = SAMPLE_INFO[type][sampleName];
found = true;
break;
}
}
if (!found) {
// If not found in SAMPLE_INFO, it might be a built-in or custom synth, so we resolve immediately
resolve();
return;
}
if (this.samples[sampleType][sampleName] !== null) {
// Already loaded
resolve();
return;
}
// Load the sample module using require
require([sampleInfo.path], () => {
try {
// eslint-disable-next-line no-undef
const sampleData = window[sampleInfo.global];
if (sampleData) {
this.samples[sampleType][sampleName] = sampleData();
resolve();
} else {
console.error(
`Global variable ${sampleInfo.global} not found for sample ${sampleName}`
);
reject(`Sample global not found: ${sampleName}`);
}
} catch (e) {
console.error(`Error processing sample ${sampleName}:`, e);
reject(e);
}
});
});
};
/**
* Preloads samples used in a project by scanning blocks for instrument names.
* This should be called when a project is loaded to avoid playback delays.
* @function
* @memberof Synth
* @param {Array} blockList - The list of blocks from the project.
* @returns {Promise<void>} - A promise that resolves when all samples are preloaded.
*/
this.preloadProjectSamples = async blockList => {
if (!blockList || !Array.isArray(blockList)) {
return;
}
const instrumentsToLoad = new Set();
// Known instrument block names
const instrumentBlockNames = ["settimbre", "setinstrument", "timbre", "instrument"];
// Scan blocks for instrument references
for (const block of blockList) {
if (!Array.isArray(block) || block.length < 2) continue;
const blockName = block[1];
// Check if this is an instrument-setting block
if (instrumentBlockNames.includes(blockName)) {
// The instrument name is usually in a connected block
// Check the connections for potential instrument names
const connections = block[4];
if (Array.isArray(connections)) {
for (const connIdx of connections) {
if (connIdx !== null && blockList[connIdx]) {
const connBlock = blockList[connIdx];
// Check if it's a text/value block with an instrument name
if (Array.isArray(connBlock) && connBlock.length > 1) {
const value = connBlock[1];
// Check if this value is a known instrument
if (typeof value === "string") {
// Check voice samples
if (SAMPLE_INFO.voice && SAMPLE_INFO.voice[value]) {
instrumentsToLoad.add(value);
}
// Check drum samples
if (SAMPLE_INFO.drum && SAMPLE_INFO.drum[value]) {
instrumentsToLoad.add(value);
}
}
}
}
}