-
Notifications
You must be signed in to change notification settings - Fork 2
/
audio-visual.js
1363 lines (1285 loc) · 46.1 KB
/
audio-visual.js
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
/*
This module manages the
sonic and visual output of the app
*/
// 3rd party
var P5 = require('p5');
require('p5/lib/addons/p5.sound');
var freqi = require('freqi');
var postal = require('postal');
var channel = postal.channel();
var appTemplate = require('../templates/codisplay.hbs');
// custom
var coDisplayData = require('./co-display-data');
var weatherCheck = require('./weather-checker-fns');
var microU = require('../utilities/micro-utilities');
var intervals = require('../utilities/intervals');
var avSettings = require('../settings/av-settings');
var makeFibSequence = require('../utilities/fib-sequence');
var coFns = require('./co-display-fns');
var pageTheme = require('./page-theme');
var audioGets = require('./audio-getters');
var audioHlpr = require('./audio-helpers');
module.exports = function() {
/*
Module scoped vars
and constants
*/
var isPlaying = false;
var maxMasterVolSet = false;
// rate
var appFrameRate = 30;
var sequenceStart = true;
var sequenceLength = 1500;
var rootNoteRate;
// bass
var bass;
var bass2;
// Windy / Brass
var brassBaritone;
var brassBaritone2;
// Percussion
var chineseCymbal;
var timpani;
var rideCymbal;
var djembe;
var djembeVolArr = [0.95, 0.7];
// clement
var harpSound;
// long notes
var longNote;
// precipitation / drops
var dropSound;
// Lead sounds
var rhodes;
// Globals
var padFilter;
var freezingFilter;
var foggyFilter;
var longNoteFilter;
var uvNoise;
// brass
var brassPanAngle = 180;
var brassSinVal = 0;
var brassCosVal = 0;
// pan
var panArr = [-0.8, 0, 0.8];
var longNotePanArr = [-0.2, 0, 0.2];
// noise
var uvNoiseAngle = 0;
var uvNoiseSinVal = 0;
// Sound objects
var padSounds = [];
var choralSounds = [];
var choralScales = [];
var synchedSoundsChords = [];
// Lead
var leadSoundIndex = 0;
// Subscriptions
var publishBrassOne;
var publishBrassTwo;
// Ramp times
var rampTime = 0.001;
var timeFromNow = 0.001;
var startVol = 0.001;
// DOM
var cdContainer = document.querySelector('.conditions-display__list');
function fadeInDisplayItem(thisDisplayItem) {
var _opacity = 0;
var _aniLoop = setInterval(function() {
if (_opacity < 1) {
thisDisplayItem.style.opacity = _opacity + '';
_opacity += 0.05;
} else {
clearInterval(_aniLoop);
}
}, 50);
}
function fadeOutDisplayItems(thisDisplayItem, index, totalItems, doneFn, autoStart) {
var _opacity = 1;
var _aniLoop = setInterval(function() {
if (_opacity > 0) {
thisDisplayItem.style.opacity = _opacity + '';
_opacity -= 0.05;
} else {
clearInterval(_aniLoop);
//when all are done
if (index + 1 === totalItems) {
//Run the callback
doneFn(autoStart);
}
}
}, 50);
}
function fadeOutPadSounds(soundItem) {
function stopPadSounds(padSound) {
setTimeout(function() {
padSound.stop();
}, avSettings.fadeTime * 1000);
}
soundItem.fade(0, avSettings.fadeTime);
stopPadSounds(soundItem);
}
function fadeOutChoralSounds(soundItem) {
soundItem.fade(0, avSettings.fadeTime);
setTimeout(function() {
soundItem.stop();
}, avSettings.fadeTime * 1000);
}
function fadeOutAllSounds(config) {
// Fades
brassBaritone.fade(0, avSettings.fadeTime);
brassBaritone2.fade(0, avSettings.fadeTime);
bass.fade(0, avSettings.fadeTime);
bass2.fade(0, avSettings.fadeTime);
chineseCymbal.fade(0, avSettings.fadeTime);
choralSounds.forEach(fadeOutChoralSounds);
djembe.fade(0, avSettings.fadeTime);
dropSound.fade(0, avSettings.fadeTime);
harpSound.fade(0, avSettings.fadeTime);
longNote.fade(0, avSettings.fadeTime);
padSounds.forEach(fadeOutPadSounds);
rhodes.fade(0, avSettings.fadeTime);
rideCymbal.fade(0, avSettings.fadeTime);
timpani.fade(0, avSettings.fadeTime);
uvNoise.fade(0, avSettings.fadeTime);
// Stop after fades
setTimeout(function() {
brassBaritone.stop();
brassBaritone2.stop();
bass.stop();
bass2.stop();
chineseCymbal.stop();
djembe.stop();
harpSound.stop();
dropSound.stop();
longNote.stop();
rhodes.stop();
rideCymbal.stop();
timpani.stop();
uvNoise.stop();
}, avSettings.fadeTime * 1000);
// Unsubs
publishBrassOne.unsubscribe();
publishBrassTwo.unsubscribe();
isPlaying = false;
if (!config.invisible) {
channel.publish('allStopped', config.autoStart);
}
}
function createP5SoundObjs() {
padFilter = new P5.LowPass();
longNoteFilter = new P5.LowPass();
freezingFilter = new P5.HighPass();
foggyFilter = new P5.HighPass();
uvNoise = new P5.Noise('pink');
}
// main app init
function init(lwData) {
console.log('lwData', lwData);
// Init scoped values
// Defaults
var mainSeqCount = 0;
var extraSeqCount = 0;
var extraSeqPlaying = false;
var brassOneScaleArrayIndex = 0;
var brassTwoScaleArrayIndex = 0;
var chordIndex = 0;
var padIndexCount = 0;
var fibIndex = 0;
var panIndex = 0;
var humidArpScales = [];
var humidArpReady = false;
var humidArpScaleIndex = 0;
var hArpSeqIndex = 0;
var padReady = false;
var leadSoundReady = false;
var precipArpScales = [];
var precipArpReady = false;
var precipArpScaleIndex = 0;
var pArpSeqIndex = 0;
var freezingFilterFreq = 2000;
var foggyFilterFreq = 750;
var masterGain = 0;
//clear data
padSounds = [];
choralSounds = [];
// grouped weather booleans
var wCheck = {
//single concept items
isPrecip: weatherCheck.isPrecip(lwData.precipIntensity.value),
isWindy: weatherCheck.isWindy(lwData.windSpeed.value),
isCloudy: weatherCheck.isCloudy(lwData.cloudCover.value),
isVisbilityPoor: weatherCheck.isVisbilityPoor(lwData.visibility.value),
isFoggy: weatherCheck.isFoggy(lwData.visibility.value, lwData.temperature.value, lwData.dewPoint.value),
//Humidity
isHumid: weatherCheck.isHumid(lwData.humidity.value),
isFreezingAndHumid: weatherCheck.isFreezingAndHumid(lwData.humidity.value, lwData.temperature.value),
isMuggy: weatherCheck.isMuggy(lwData.humidity.value, lwData.temperature.value),
isSmoggy: weatherCheck.isSmoggy(lwData.humidity.value, lwData.apparentTemperature.value, lwData.visibility.value),
isArid: weatherCheck.isArid(lwData.humidity.value, lwData.temperature.value, lwData.precipIntensity.value),
isCrisp: weatherCheck.isCrisp(lwData.humidity.value, lwData.temperature.value),
isSirocco: weatherCheck.isSirocco(lwData.humidity.value, lwData.temperature.value, lwData.windSpeed.value),
//temperature
isCold: weatherCheck.isCold(lwData.temperature.value),
isFreezing: weatherCheck.isFreezing(lwData.temperature.value),
isWayBelowFreezing: weatherCheck.isWayBelowFreezing(lwData.temperature.value),
//broad conditions
isMild: weatherCheck.isMild(lwData.temperature.value, lwData.windSpeed.value),
isMildAndBreezy: weatherCheck.isMildAndBreezy(lwData.temperature.value, lwData.windSpeed.value),
isMildAndHumid: weatherCheck.isMildAndHumid(lwData.temperature.value, lwData.windSpeed.value, lwData.humidity.value),
isFine: weatherCheck.isFine(lwData.cloudCover.value, lwData.windSpeed.value, lwData.temperature.value),
isSublime: weatherCheck.isSublime(lwData.cloudCover.value, lwData.windSpeed.value, lwData.temperature.value),
isClement: weatherCheck.isClement(lwData.cloudCover.value, lwData.windSpeed.value, lwData.precipIntensity.value),
isBitter: weatherCheck.isBitter(lwData.temperature.value, lwData.windSpeed.value),
isStormy: weatherCheck.isStormy(lwData.cloudCover.value, lwData.windSpeed.value, lwData.precipIntensity.value),
isViolentStorm: weatherCheck.isViolentStorm(lwData.cloudCover.value,lwData.windSpeed.value, lwData.precipIntensity.value),
isOminous: weatherCheck.isOminous(lwData.cloudCover.value, lwData.nearestStormDistance.value, lwData.precipProbability.value)
};
console.log('wCheck', wCheck);
// grouped sound booleans
// Only require these three as
// all other sounds rely on just one condition
var sCheck = {
harpCanPlay : audioGets.getHarpCanPlay(wCheck),
timpaniCanPlay : audioGets.getTimpaniCanPlay(wCheck),
choralCanPlay : audioGets.getChoralCanPlay(wCheck)
};
// Get and set core values
var numPadNotes = audioGets.getNumPadNotes(wCheck, avSettings);
var numChords = audioGets.getNumChords(lwData, avSettings).numChords;
var numExtraChords = audioGets.getNumChords(lwData, avSettings).numExtraChords;
var chordNumGreatest = numChords > numExtraChords ? numChords : numExtraChords;
var numSemisPerOctave = audioGets.getNumSemisPerOctave(avSettings, wCheck);
// Root note
// Is an index rather than a frequency
var rootNoteRange = audioGets.getRootNoteRange(numSemisPerOctave);
var rootNote = audioGets.getRootNote(lwData.pressure, rootNoteRange);
console.log('rootNote', rootNote);
var rootNoteHigh = audioGets.isRootNoteHigh(rootNote);
var rootNoteGrtrMedian = audioGets.isRootNoteGrtrMedian(rootNote, rootNoteRange);
// Chord seq or inversion types
var chordSeqKey = audioGets.getChordSeqKey(wCheck, rootNoteGrtrMedian);
var chordType = audioGets.getChordType(wCheck, chordSeqKey);
var isMelodyMajor = audioGets.isMelodyMajor(chordSeqKey, chordType);
console.log('chordSeqKey', chordSeqKey);
console.log('chordType', chordType);
console.log('isMelodyMajor', isMelodyMajor);
var upperMult = audioGets.getSeqRepeatMaxMult(numChords, avSettings);
var seqRepeatNum = audioGets.getMainSeqRepeatNum(lwData.apparentTemperature, numChords, upperMult);
// Precipitation
// TODO Group these into object
// and only create it if it's raining
var precipCategory = audioGets.getPrecipCategory(lwData.precipType);
var precipArpBpm = audioGets.getPrecipArpBpm(lwData.precipIntensity);
var precipArpBps = precipArpBpm / 60;
var precipArpStepTime = Math.round(appFrameRate / precipArpBps);
var precipArpIntervalType = audioGets.getPrecipArpIntervalType(isMelodyMajor);
var leadVolume = audioGets.getLeadSoundVolume(wCheck.isSublime);
var padType = audioGets.getPadType(wCheck);
var padVolume = audioGets.getPadVolume(wCheck, sCheck, padType, avSettings);
var inversionOffsetType = audioGets.getInversionOffsetKey(wCheck, chordSeqKey);
// Humidity
// TODO Group these into object
// and only create it if it's humid
var humidArpBpm = audioGets.getHumidArpBpm(lwData.humidity);
var humidArpBps = humidArpBpm / 60;
var humidArpStepTime = Math.round(appFrameRate / humidArpBps);
var humidArpIntervalsKey = audioGets.getHumidArpIntervals(lwData, isMelodyMajor);
var harpVolArr = audioGets.getHarpVolArr(wCheck, sCheck);
// Long note
var longNoteIndex = audioGets.getLongNoteIndex(lwData.windBearing, numPadNotes);
var longNoteHigh = audioGets.isLongNoteHigh(rootNoteHigh, longNoteIndex, numPadNotes);
var longNoteVolArr = audioGets.getLongNoteVolArr(wCheck);
var longNoteType = audioGets.getLongNoteType(wCheck);
console.log('longNoteType', longNoteType);
var longNoteFilterFreq = audioGets.getLongNoteFilterFreq(lwData.visibility, avSettings.longNoteFilter);
var padFilterFreq = audioGets.getPadFilterFreq(lwData, avSettings);
var extraSeqOffset = audioGets.getExtraChordsOffset(rootNoteGrtrMedian, numSemisPerOctave);
var invExtraSeqOffset = numSemisPerOctave - extraSeqOffset;
// TODO Group these into object
// and only create it if it's windy
var brassBaritoneVol = audioGets.getBrassVolume(lwData.windSpeed);
var brassBaritoneBpm = audioGets.getBrassBpm(lwData.windSpeed);
var brassBaritoneBps = brassBaritoneBpm / 60;
var brassBaritoneStepTime = Math.round(appFrameRate / brassBaritoneBps);
var brassBaritone2StepTime = brassBaritoneStepTime * 2 + 57;
// Ride
var rideCymbalRate = audioGets.getRideCymbalRate(lwData);
var rideCymbalBpm = audioGets.getRideCymbalsBpm(lwData);
var rideCymbalBps = rideCymbalBpm / 60;
var rideCymbalStepTime = Math.round(appFrameRate / rideCymbalBps);
var rideCymbalMaxVolume = audioGets.getRideCymbalMaxVolume(lwData);
var rideCymbalVolumeArr = audioGets.getRideCymbalVolumeArr(rideCymbalMaxVolume);
var djembeStepTime = rideCymbalStepTime * 2;
var noteLengthMult = audioGets.getNoteLengthMult(lwData, avSettings);
var noteLengths = audioGets.getNoteLengths(appFrameRate, noteLengthMult);
var leadNoteLengthStart = audioGets.getLeadNoteLengthStart(appFrameRate, lwData);
var leadNoteLengths = makeFibSequence(leadNoteLengthStart, numPadNotes * 2);
// Choral
var choralSoundVol = audioGets.getChoralSoundVol(wCheck);
var choralDenominator = wCheck.isFreezing ? 2 : 1;
var choralExtraDenominator = rootNoteGrtrMedian ? 2 : 1;
// noise
var uvNoiseMaxVol = audioGets.getUvNoiseMaxVol(lwData);
//Set initial note lengths for use in draw
var currNoteLength = noteLengths[0];
var currLeadLength = leadNoteLengths[0];
//Create p5 sketch
var myP5 = new P5(function(sketch) {
// used for Brass pan
// and uv noise
var brassAngleInc = sketch.TWO_PI / 150;
var noiseAngleInc = sketch.TWO_PI / 340;
channel.subscribe('allStopped', function() {
sketch.noLoop();
});
/**
* ------------------------
* Set base effects
* ------------------------
*/
function setPadFilter() {
padFilter.freq(padFilterFreq);
padFilter.res(20);
}
function setLongNoteFilter() {
longNoteFilter.freq(longNoteFilterFreq);
longNoteFilter.res(10);
}
/**
* ------------------------
* Music loop index updaters
* ------------------------
*/
function updatePanIndex() {
if (panIndex < panArr.length - 1) {
panIndex++;
} else {
panIndex = 0;
}
}
function setChordIndex() {
if (chordIndex >= synchedSoundsChords.length - 1 - numExtraChords) {
chordIndex = 0;
} else {
chordIndex++;
}
return chordIndex;
}
function updateNoteLength() {
//If the lower chords are playing halve the time
currNoteLength = extraSeqPlaying ? sketch.random(noteLengths) * 2 :
sketch.random(noteLengths);
//Start the call of the updateNoteLength fn again
padReady = true;
}
//Set amount of time each lead note
//plays using fibonacci sequence
function updateLeadSoundLength() {
currLeadLength = leadNoteLengths[fibIndex];
if (fibIndex === leadNoteLengths.length - 1) {
fibIndex = 0;
} else {
fibIndex++;
}
leadSoundReady = true;
}
function updateLeadSoundIndex() {
if (leadSoundIndex === numPadNotes - 1) {
leadSoundIndex = 0;
} else {
leadSoundIndex++;
}
}
/**
* ------------------------
* Music preparation functions
* ------------------------
*/
function prepareHumidArp(hScalesNoRests) {
// Overwrite empty array with sequences
// that include rests
humidArpScales = hScalesNoRests.map(function(hArpScale) {
return audioHlpr.getAllegrettoRhythmType(wCheck, hArpScale);
});
}
function preparePrecipArp(precipArpScaleNoRests) {
// Overwrite sequence with new notes
precipArpScales = precipArpScaleNoRests.map(function(pArpScale) {
return audioHlpr.addRandomStops(pArpScale, sketch).reverse();
});
}
/**
* ------------------------
* Music playback functions
* ------------------------
*/
// Used with the two mechanisms
// for pad playback
function moveToNextChord() {
// increment indices
setChordIndex();
}
function playBrassBaritone(scale, doublePitch) {
var pitchMult = 1;
if (doublePitch) {
pitchMult = 2;
}
brassBaritone.play();
brassBaritone.setVolume(brassBaritoneVol, rampTime, timeFromNow, startVol);
brassBaritone.rate(scale[brassOneScaleArrayIndex] * pitchMult);
if (brassOneScaleArrayIndex >= 1) {
brassOneScaleArrayIndex = 0;
} else {
brassOneScaleArrayIndex++;
}
}
function playBrassBaritoneTwo(scale, doublePitch) {
var pitchMult = 1;
if (doublePitch) {
pitchMult = 2;
}
var _newScaleArr = scale.slice().reverse();
var _brassBaritoneTwoRate;
if (rootNoteGrtrMedian) {
var _rateMultArr = [1, 2];
var _randomRateMultVal = sketch.random(_rateMultArr);
_brassBaritoneTwoRate = _newScaleArr[brassTwoScaleArrayIndex] * _randomRateMultVal;
} else {
_brassBaritoneTwoRate = _newScaleArr[brassTwoScaleArrayIndex];
}
brassBaritone2.play();
brassBaritone2.setVolume(0.4, rampTime, timeFromNow, startVol);
brassBaritone2.rate(_brassBaritoneTwoRate * pitchMult);
if (brassTwoScaleArrayIndex >= scale.length - 1) {
brassTwoScaleArrayIndex = 0;
} else {
brassTwoScaleArrayIndex++;
}
}
function playLongNote() {
//playlogic
var _longNoteRate = synchedSoundsChords[chordIndex][longNoteIndex];
var _longNoteVol;
// playlogic
// If weather is hot, dry and clear
// play the longNote very quietly
if (wCheck.isSublime) {
_longNoteVol = longNoteVolArr[0];
} else {
_longNoteVol = sketch.random(longNoteVolArr);
}
// Lower by one octave
// if the lower chords are playing
// TODO add wCheck.isFreezing? So flute isnt so ugly
if (extraSeqPlaying || longNoteHigh || wCheck.isFreezingAndHumid || longNoteType === 'shiney') {
_longNoteRate = _longNoteRate / 2;
}
// playlogic
// play full note if visibility is poor
// and the weather is inclement
// Clement weather is full pad notes
if (!wCheck.isVisbilityPoor || !wCheck.isClement) {
longNote.playMode('restart');
}
longNote.disconnect();
longNote.connect(longNoteFilter);
longNote.play();
longNote.pan(sketch.random(longNotePanArr));
longNote.setVolume(_longNoteVol, rampTime, timeFromNow, startVol);
longNote.rate(_longNoteRate);
}
function playBass() {
// Play 1st note of each chord
var _bassRate = synchedSoundsChords[chordIndex][0];
bass.playMode('restart');
bass.play();
bass.setVolume(1, rampTime, timeFromNow, startVol);
bass.rate(_bassRate);
}
function padCallBack() {
if (isPlaying) {
padIndexCount++;
// When all the sounds have played once, loop
if (padIndexCount === padSounds.length) {
moveToNextChord();
playSynchedSounds(true);
padIndexCount = 0;
}
}
}
function playPad(playFullNotes) {
console.log('playFullNotes?', playFullNotes);
for (var i = 0, length = padSounds.length; i < length; i++) {
// TODO can we connect in setup?
// padVolume = 0.01;
padSounds[i].disconnect();
padSounds[i].connect(padFilter);
padSounds[i].pan(panArr[panIndex]);
padSounds[i].playMode('restart');
padSounds[i].play();
padSounds[i].setVolume(padVolume, rampTime, timeFromNow, startVol);
padSounds[i].rate(synchedSoundsChords[chordIndex][i]);
// If we want to play the play full note length
// use the onended callback
if (playFullNotes) {
padSounds[i].onended(padCallBack);
}
updatePanIndex();
}
}
function playSynchedSounds(playFullNotes) {
// Master sequence
if (mainSeqCount === seqRepeatNum && numExtraChords > 0) {
//If we've played the whole sequence
//seqRepeatNum number of times
//play the first chord of extraChords
chordIndex = synchedSoundsChords.length - numExtraChords + extraSeqCount;
extraSeqCount++;
extraSeqPlaying = true;
//Once we've played all the extraChords
//start over
if (extraSeqCount === numExtraChords) {
mainSeqCount = 0;
extraSeqCount = 0;
}
} else {
extraSeqPlaying = false;
mainSeqCount++;
}
// Play the pad chord
// and pass in the playback mode
playPad(playFullNotes);
// playlogic
// Avoid sound clash with Brass
if (wCheck.isCloudy && !wCheck.isWindy) {
playBass();
}
if (!wCheck.isWindy) {
playLongNote();
}
}
function playChoralSound() {
// TODO consider for loop for speed
choralSounds.forEach(function(choralSound, i) {
// playlogic
if (wCheck.isFreezing) {
choralSound.disconnect();
choralSound.connect(freezingFilter);
}
// must loop before rate is set
// issue in Chrome only
choralSound.loop();
choralSound.rate(choralScales[0][i] / choralDenominator);
choralSound.setVolume(choralSoundVol, rampTime, timeFromNow, startVol);
});
}
/**
* playSounds Handles playback logic
* Though some of this is delegated
* @param {Array} pArpScalesNoRests a set of notes fot the sequencer to play
* @param {Array} hScalesNoRests a set of notes fot the sequencer to play
* @return {boolean} default value
*/
function playSounds(invisible) {
// playlogic
// Only the first chord is passed in
if (sCheck.choralCanPlay) {
playChoralSound();
}
// Play the lead if the weather is fine
// but not raining so as to avoid clash
if (wCheck.isFine && !wCheck.isPrecip) {
leadSoundReady = true;
}
// Play brass
publishBrassOne = channel.subscribe('triggerBrassOne', function(data) {
console.log('data', data);
playBrassBaritone(synchedSoundsChords[chordIndex], data.doublePitch);
});
publishBrassTwo = channel.subscribe('triggerBrassTwo', function(data) {
console.log('data', data);
playBrassBaritoneTwo(synchedSoundsChords[chordIndex], data.doublePitch);
});
// SynchedSounds are pads, long note and bass
// playlogic
if (wCheck.isClement) {
// Play full length of notes
playSynchedSounds(true);
padReady = false;
} else {
// Play the pad sounds
// using the draw loop
padReady = true;
}
// Humid arpeggio
if (humidArpScales.length > 0) {
humidArpReady = true;
}
// Precipitation arpeggio
if (precipArpScales.length > 0) {
precipArpReady = true;
}
uvNoise.amp(0);
uvNoise.start();
// Tell rest of app we're playing
isPlaying = true;
// If inactive tab stopped playback
if (!invisible) {
channel.publish('playing', lwData.name);
}
}
/**
* ------------------------
* Scale creation functions
* ------------------------
*/
function getChordSeqOffsetArr(numChords) {
var _chordOffsetArr = [];
var _diff;
_chordOffsetArr = intervals[chordSeqKey];
// error check
if (numChords > _chordOffsetArr.length) {
_diff = numChords - _chordOffsetArr.length;
_chordOffsetArr = freqi.augmentNumArray({
originalArray: _chordOffsetArr,
difference: _diff,
repeatMultiple: 0,
amountToAdd: 0
});
}
return _chordOffsetArr;
}
function getInversionOffsetArr(numChords) {
var _chordInversionOffSetArr = intervals[inversionOffsetType];
console.log('_chordInversionOffSetArr', _chordInversionOffSetArr);
var _diff;
if (numChords > _chordInversionOffSetArr.length) {
_diff = numChords - _chordInversionOffSetArr.length;
_chordInversionOffSetArr = freqi.augmentNumArray({
originalArray: _chordInversionOffSetArr,
difference: _diff,
repeatMultiple: 0,
amountToAdd: 0
});
}
return _chordInversionOffSetArr;
}
// If the key's not from a sequence
// i.e. it's an inversion
// then get the generic chord type
function getValidChordType(key) {
var _chordType;
// If there's a property called key
// i.e. we're using the chord seqs
// use it
if (key) {
_chordType = key;
} else {
_chordType = chordType;
}
return _chordType;
}
function makeChordSequence() {
var _chordSeq = [];
// Chord shift
var _chordSeqOffsetArr = getChordSeqOffsetArr(chordNumGreatest);
// Chord inversion shift
var _inversionOffsetArr = getInversionOffsetArr(chordNumGreatest);
// Create primary chords
for (var i = 0; i < numChords; i++) {
_chordSeq.push(freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: numPadNotes,
rootNote: _chordSeqOffsetArr[i].index + rootNote,
intervals: intervals[getValidChordType(_chordSeqOffsetArr[i].key)],
intervalStartIndex: _inversionOffsetArr[i],
amountToAdd: numSemisPerOctave,
repeatMultiple: 0,
type: 'pad'
}));
}
// Create extra sequence chord(s)
for (var j = 0; j < numExtraChords; j++) {
_chordSeq.push(freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: numPadNotes,
rootNote: _chordSeqOffsetArr[j].index - extraSeqOffset + rootNote,
intervals: intervals[getValidChordType(_chordSeqOffsetArr[j].key)],
intervalStartIndex: _inversionOffsetArr[j],
amountToAdd: numSemisPerOctave,
repeatMultiple: 0,
type: 'pad extra'
}));
}
return _chordSeq;
}
function createChoralScales() {
var _choralScales = [];
var _mainChoralScale = freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: choralSounds.length,
rootNote: rootNote,
intervals: intervals.heptatonicMajorIntervals,
intervalStartIndex: 0,
amountToAdd: 0,
repeatMultiple: 0,
type: 'choral'
});
var _extraChoralScale = freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: choralSounds.length,
rootNote: rootNote - extraSeqOffset,
intervals: intervals.heptatonicMajorIntervals,
intervalStartIndex: 0,
amountToAdd: 0,
repeatMultiple: 0,
type: 'choral extra'
});
_choralScales.push(_mainChoralScale, _extraChoralScale);
return _choralScales;
}
function createHumidArpScales() {
var _hArpScalesNoRests = [];
var _numHumidArpNotes = intervals[humidArpIntervalsKey].length;
var _mainHArpScale = freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: _numHumidArpNotes,
rootNote: rootNote,
intervals: intervals[humidArpIntervalsKey],
intervalStartIndex: 0,
amountToAdd: 0,
repeatMultiple: 0,
type: 'humid arp'
});
var _extraHArpScale = freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: _numHumidArpNotes,
rootNote: rootNote + invExtraSeqOffset,
intervals: intervals[humidArpIntervalsKey],
intervalStartIndex: 0,
amountToAdd: 0,
repeatMultiple: 0,
type: 'humid arp extra'
});
_hArpScalesNoRests.push(_mainHArpScale, _extraHArpScale);
return _hArpScalesNoRests;
}
function createPrecipArpScales() {
var _pArpScalesNoRests = [];
var _pArpCNoteOffset = -Math.abs(numSemisPerOctave * 2) + rootNote;
// When adding missing values
// go up two octaves
var _repeatMultiple = 2;
var _mainPArpScale = freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: avSettings.numPrecipArpNotes,
rootNote: _pArpCNoteOffset,
intervals: intervals[precipArpIntervalType],
intervalStartIndex: 0,
amountToAdd: numSemisPerOctave,
repeatMultiple: _repeatMultiple,
type: 'precip arp'
});
var _extraPArpScale = freqi.getFreqs({
startFreq: 1,
numSemitones: numSemisPerOctave,
numNotes: avSettings.numPrecipArpNotes,
rootNote: _pArpCNoteOffset + invExtraSeqOffset,
intervals: intervals[precipArpIntervalType],
intervalStartIndex: 0,
amountToAdd: numSemisPerOctave,
repeatMultiple: _repeatMultiple,
type: 'precip arp extra'
});
_pArpScalesNoRests.push(_mainPArpScale, _extraPArpScale);
return _pArpScalesNoRests;
}
/*
Create necessary scales
*/
function configureSounds() {
var _pArpScalesNoRests = [];
var _hArpScalesNoRests = [];
// Make arrays of frequencies for playback
synchedSoundsChords = makeChordSequence();
// Set filter for pad sounds
setPadFilter();
setLongNoteFilter();
// Set the root note rate
// for use elsewhere in program
rootNoteRate = synchedSoundsChords[chordIndex][0];
// playlogic
if (wCheck.isPrecip) {
_pArpScalesNoRests = createPrecipArpScales();
preparePrecipArp(_pArpScalesNoRests);
}
// Humid arpeggio will not play if
// other lead sounds are playing
if (sCheck.harpCanPlay) {
_hArpScalesNoRests = createHumidArpScales();
prepareHumidArp(_hArpScalesNoRests);
}
if (sCheck.choralCanPlay) {
choralScales = createChoralScales();
}
playSounds();
}
/**
* ------------------------
* Display creation functions
* ------------------------
*/
function formatMusicalValStrings(displayData) {
return displayData.map(function(displayProp) {
var _musicValueLowerCase;
var _musicValue;
//Add spaces where necessary
if (typeof displayProp.musicValue === 'string') {
_musicValue = microU.addSpacesToString(displayProp.musicValue);
if (displayProp.musicKey !== 'rootNote') {
_musicValueLowerCase = microU.strToLowerCase(_musicValue);
} else {
_musicValueLowerCase = _musicValue;
}
displayProp.musicValue = microU.removeStrFromStart('inversions', _musicValueLowerCase);
}
return displayProp;
});
}
function formatWCheckBools(displayData) {
return displayData.map(function(displayProp) {
// Remove boolean values
if (displayProp.value === true) {
displayProp.value = '';
}
return displayProp;
});
}
function buildDisplay(coDisplayData) {
// Format strings and numbers
var _formattedMusicValData = formatMusicalValStrings(coDisplayData);
var _formattedWCheckBools = formatWCheckBools(_formattedMusicValData);
// TODO perf - should use for loop for speed?
_formattedWCheckBools.forEach(function(coDisplayObj) {
//Only show true or valid values
//Zero is valid for most conditions
if (coDisplayObj.value !== undefined && coDisplayObj.value !==
false) {
//filter out negative values that are true
//or don't exist
if (coDisplayObj.negativeValue === undefined || coDisplayObj.negativeValue === false) {
var _itemTmpl = appTemplate(coDisplayObj);
cdContainer.insertAdjacentHTML('beforeend', _itemTmpl);
var _lastItem = cdContainer.lastElementChild;
fadeInDisplayItem(_lastItem);
}
} else {
//'Not displayed because not defined or false ', coProp);
}
});
}
function getDisplayDataVals() {
return {
numChords: numChords,
numExtraChords: numExtraChords,
numSemisPerOctave: numSemisPerOctave,
rootNote: rootNote,
noteLengthMult: noteLengthMult,
padFilterFreq: padFilterFreq,
seqRepeatNum: seqRepeatNum,
longNoteIndex: longNoteIndex,
longNoteFilterFreq: longNoteFilterFreq,
precipArpBpm: precipArpBpm,
precipCategory: precipCategory,
uvNoiseMaxVol: uvNoiseMaxVol,
rideCymbalBpm: rideCymbalBpm,
rideCymbalRate: rideCymbalRate,
rideCymbalMaxVolume: rideCymbalMaxVolume * 10,
humidArpBpm: humidArpBpm,
humidArpIntervalsKey: humidArpIntervalsKey,
chordType: chordType,
chordSeqKey: chordSeqKey,
padType: padType,
longNoteType: longNoteType,
inversionOffsetType: inversionOffsetType,
numPadNotes: numPadNotes
};
}
// Only used if web worker is not available
function configureDisplay(musicDisplayVals) {
// Set the data vals using
// module scoped data
var _setCoDisplayGroupVals = coFns(
coDisplayData,
lwData,
wCheck,
musicDisplayVals
);
var _finalCoData = _setCoDisplayGroupVals();
buildDisplay(_finalCoData);
}
function configureAudioVisual() {
var _musicDisplayVals = getDisplayDataVals();
var _firstLoad = true;
//Create a thread to set
//values for display
if (window.Worker) {
var WebWorker = require('./display.worker.js');
var displayWorker = new WebWorker();
displayWorker.addEventListener('message', function(result) {
console.log('result', result);
buildDisplay(result.data);
displayWorker.terminate();
if (_firstLoad) {
// revoke the Object URL that was used to create this worker,
// so as not to leak it
URL.revokeObjectURL(displayWorker.objectURL);
_firstLoad = false;
}
});
displayWorker.onerror = function(e) {
console.log('Error with web worker on ' + 'Line #' + e.lineno +' - ' + e.message + ' in ' + e.filename);