-
Notifications
You must be signed in to change notification settings - Fork 3
/
SoundAnalyse.js
1472 lines (1293 loc) · 52.5 KB
/
SoundAnalyse.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
/**
* @author Zharko Simonovski <zarko.simonovski@gmail.com>
* @copyright 2015 Zharko Simonovski
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Enable you to create sound analyse object and get audio data
* You can create graphical sound analyse sprite which will auto draw your selection: char, time frequency line, stereo or audio bar, background gradient...
* You can also create a audio analyse sprite with graphic representation
*
* @class Phaser.Plugin.SoundAnalyze
* @constructor
* @param {Phaser.Game} game - Game reference to the currently running game.
* @return {Phaser.Plugin.SoundAnalyze}
*/
Phaser.Plugin.SoundAnalyse = function (game) {
Phaser.Plugin.call(this, game);
/** --- SOUND ANALYSER --- **/
/**
* The Sound Analyser class constructor.
*
* @class Phaser.SoundAnalyser
* @extends Phaser.Sound
* @constructor
* @param {Phaser.Game} game - Reference to the current game instance.
* @param {string} key - Asset key for the sound.
* @param {number} [volume=1] - Default value for the volume, between 0 and 1.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @param {boolean} [allowFakeData=false] - If true and sound analyse is not supported, it will allow fake data generation so you can still have some visualization
*/
Phaser.SoundAnalyser = function (game, key, volume, loop, connect, allowFakeData) {
// call base object constructor
Phaser.Sound.call(this, game, key, volume, loop, connect);
/**
* @property {Boolean} allowFakeData - If true and sound analyse is not supported, it will allow fake data generation so you can still have some visualization
*/
this.allowFakeData = true;//allowFakeData === true;
/**
* @property {object} analyserNode - The analyser node in a Web Audio system, node which is able to provide real-time frequency and time-domain analysis information
*/
this.analyserNode = null;
/**
* @property {object} spliterNode - The splitter node in a Web Audio system, node which will separate audio data to two channels (left/right stereo)
*/
this.spliterNode = null;
/**
* @property {object} splitAnalyseNodeLeft - The analyser node in a Web Audio system, node which is able to provide real-time frequency and time-domain analysis information for the left channel from splitter
*/
this.splitAnalyseNodeLeft = null;
/**
* @property {object} splitAnalyseNodeRight - The analyser node in a Web Audio system, node which is able to provide real-time frequency and time-domain analyse information for the right channel from splitter
*/
this.splitAnalyseNodeRight = null;
/**
* @private
* @property {Uint8Array<Number>} _dataArray - Array to store float frequency data
*/
this._dataArray = null;
/**
* @private
* @property {Uint8Array<Number>} _dataTimeArray - Array to store time frequency data
*/
this._dataTimeArray = null;
/**
* @private
* @property {Number} _bufferLength - The number of data values you will have to play with for the visualization
*/
this._bufferLength = 0;
/**
* @property {Array<Phaser.BitmapDataSoundAnalyze>} bmpSoundAnalyze - Array of bitmap data that will visualize audio analyse (equalizer, meter, volume)
*/
this.bmpSoundAnalyze = [];
/**
* @property {Phaser.Signal} onAnalyseUpdate - The onAnalyseUpdate event is dispatched when new data is analysed.
*/
this.onAnalyseUpdate = new Phaser.Signal();
/**
* @property {Boolean} supportAnalyse - If true then audio analyse is supported
*/
this.supportAnalyse = false;
/**
* @private
* @property {Number[32..2048]} _fastFourierTransform - value representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain (this will be the size of the array), must be power of 2 and in range 32 to 2048
*/
this._fastFourierTransform = 2048;
/**
* @name Phaser.SoundAnalyser#fastFourierTransform
* @property {Number} fastFourierTransform - value representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain (this will be the size of the array), must be power of 2 and in range 32 to 2048
* @readonly
*/
Object.defineProperty(Phaser.SoundAnalyser.prototype, "fastFourierTransform", {
get: function () {
return this._fastFourierTransform;
},
set: function (val) {
if (typeof val === "number" && val >= 32 && val <= 2048 && val % 2 === 0 ) {
val = Math.round(val);
this._fastFourierTransform = val;
this._bufferLength = val;
if (this.supportAnalyse) {
this.analyserNode.fftSize = val;
}
} else {
if (console.warn) {
console.warn("Provided 'fastFourierTransform' value (" + val + ") must be in range 32..2048 and power of 2!");
} else {
console.log("Warning: Provided 'fastFourierTransform' value (" + val + ") must be in range 32..2048 and power of 2!");
}
}
}
});
/**
* @private
* @property {Number} [_minDecibels=-150] - value representing the minimum power value in the scaling range for the FFT analysis data
*/
this._minDecibels = -150;
/**
* @name Phaser.SoundAnalyser#minDecibels
* @property {Number} minDecibels - value representing the minimum power value in the scaling range for the FFT analysis data
* @readonly
*/
Object.defineProperty(Phaser.SoundAnalyser.prototype, "minDecibels", {
get: function () {
return this._minDecibels;
},
set: function (val) {
if (typeof val === "number") {;
this._minDecibels = val;
if (this.supportAnalyse) {
this.analyserNode.minDecibels = val;
}
} else {
if (console.warn) {
console.warn("Provided 'minDecibels' value (" + val + ") must be number!");
} else {
console.log("Warning: Provided 'minDecibels' value (" + val + ") must be number!");
}
}
}
});
/**
* @private
* @property {Number} [_maxDecibels=10] - value representing the maximum power value in the scaling range for the FFT analysis data
*/
this._maxDecibels = 10;
/**
* @name Phaser.SoundAnalyser#maxDecibels
* @property {Number} maxDecibels - value representing the maximum power value in the scaling range for the FFT analysis data
* @readonly
*/
Object.defineProperty(Phaser.SoundAnalyser.prototype, "maxDecibels", {
get: function () {
return this._maxDecibels;
},
set: function (val) {
if (typeof val === "number") {;
this._maxDecibels = val;
if (this.supportAnalyse) {
this.analyserNode.maxDecibels = val;
}
} else {
if (console.warn) {
console.warn("Provided 'maxDecibels' value (" + val + ") must be number!");
} else {
console.log("Warning: Provided 'maxDecibels' value (" + val + ") must be number!");
}
}
}
});
// setup analyse node
if (this.context && this.context.createAnalyser) {
this.supportAnalyse = true;
// create analyse node
this.analyserNode = this.context.createAnalyser();
// setup some default values
this.analyserNode.fftSize = this._fastFourierTransform; // Fast Fourier Transform to be used to determine the frequency domain
this._bufferLength = this.analyserNode.frequencyBinCount;
this._dataArray = new Uint8Array(this._bufferLength);
this._dataTimeArray = new Uint8Array(this._bufferLength);
this.analyserNode.minDecibels = this._minDecibels;
this.analyserNode.maxDecibels = this._maxDecibels;
this.analyserNode.smoothingTimeConstant = 0.8;
// connect analyse node with gain node
this.gainNode.connect(this.analyserNode);
// create splitter node and left and right analysers
if (this.context.createChannelSplitter) {
// setup a analyser
this.splitAnalyseNodeLeft = this.context.createAnalyser();
this.splitAnalyseNodeLeft.smoothingTimeConstant = 0.8;
this.splitAnalyseNodeLeft.fftSize = this._fastFourierTransform;
this.splitAnalyseNodeRight = this.context.createAnalyser();
this.splitAnalyseNodeRight.smoothingTimeConstant = 0.8;
this.splitAnalyseNodeRight.fftSize = this._fastFourierTransform;
// create splitter
this.spliterNode = this.context.createChannelSplitter(2);
// connect one of the outputs from the splitter to the analyser
this.gainNode.connect(this.spliterNode);
this.spliterNode.connect(this.splitAnalyseNodeLeft, 0, 0);
this.spliterNode.connect(this.splitAnalyseNodeRight, 1, 0);
}
} else if (this.allowFakeData) {
this._bufferLength = this._fastFourierTransform;
this._dataArray = new Uint8Array(this._bufferLength);
this._dataTimeArray = new Uint8Array(this._bufferLength);
}
};
// constructor setup
Phaser.SoundAnalyser.prototype = Object.create(Phaser.Sound.prototype);
Phaser.SoundAnalyser.prototype.constructor = Phaser.SoundAnalyser;
/**
* Called automatically by Phaser.SoundManager to update sound analyse data
* @method Phaser.Sound#update
* @protected
*/
Phaser.SoundAnalyser.prototype.update = function () {
// call base method update
Phaser.Sound.prototype.update.call(this);
if (this.isPlaying) {
var arrayLeft, arrayRight, volMeter;
if (this.analyserNode) {
// get byte frequency array data
this.analyserNode.getByteFrequencyData(this._dataArray);
// get byte time frequency array data
this.analyserNode.getByteTimeDomainData(this._dataTimeArray);
// get the average for the first channel
var arrayLeft = new Uint8Array(this.splitAnalyseNodeLeft.frequencyBinCount);
this.splitAnalyseNodeLeft.getByteFrequencyData(arrayLeft);
var averageLeft = this.getAvg(arrayLeft);
// get the average for the second channel
var arrayRight = new Uint8Array(this.splitAnalyseNodeRight.frequencyBinCount);
this.splitAnalyseNodeRight.getByteFrequencyData(arrayRight);
var averageRight = this.getAvg(arrayRight);
// calculate volume meter
volMeter = this.getAvg(this._dataArray);
} else if (this.allowFakeData) {
var fakeData = this.getFakeData(this._bufferLength);
this._dataArray = fakeData;
this._dataTimeArray = fakeData;
// get the average for the first channel
averageLeft = this.getAvg(fakeData);
// get the average for the second channel
averageRight = fakeData;
// calculate volume meter
volMeter = fakeData;
}
if (this.analyserNode || this.allowFakeData) {
// dispatch event
this.onAnalyseUpdate.dispatch(this._dataArray, this._dataTimeArray, this._bufferLength, volMeter, averageLeft, averageRight);
// call bitmap update if provided
if (this.bmpSoundAnalyze.length > 0) {
for (var k = 0; k < this.bmpSoundAnalyze.length; ++k) {
this.bmpSoundAnalyze[k].updateAnalyse(this._dataArray, this._dataTimeArray, this._bufferLength, volMeter, averageLeft, averageRight);
}
}
}
}
};
/**
* Add new bitmap sound analyse object
*
* @method Phaser.SoundAnalyser#addBitmapSoundAnalyse
* @property {BitmapDataSoundAnalyze} bmp - bitmap sound analyse object to be add
* @return {Phaser.SoundAnalyser} return self reference
* @protected
*/
Phaser.SoundAnalyser.prototype.addBitmapSoundAnalyse = function (bmp) {
this.bmpSoundAnalyze.push(bmp);
return this;
};
/**
* Remove bitmap sound analyse object
*
* @method Phaser.SoundAnalyser#removeBitmapSoundAnalyse
* @property {BitmapDataSoundAnalyze} bmp - bitmap sound analyse object to be removed
* @return {Phaser.SoundAnalyser} return self reference
* @protected
*/
Phaser.SoundAnalyser.prototype.removeBitmapSoundAnalyse = function (bmp) {
for (var k = this.bmpSoundAnalyze.length - 1; k >= 0; --k) {
if (this.bmpSoundAnalyze[k] === bmp) {
this.bmpSoundAnalyze.splice(k, 1);
break;
}
}
return this;
};
/**
* Called automatically by Phaser.SoundManager. to get average sound meter value
* @method Phaser.SoundAnalyser#getAvg
* @property {Uint8Array<Number>} dataArr - array with sound frequency data
* @return {Number} return average frequency value
* @protected
*/
Phaser.SoundAnalyser.prototype.getAvg = function (dataArr) {
var values = 0;
var average;
var length = dataArr.length;
// get all the frequency amplitudes
for (var i = 0; i < length; i++) {
values += dataArr[i];
}
average = Math.floor(values / length, 10);
return average;
};
/**
* Generate Fake frequency array data
*
* @method Phaser.AudioSprite#getFakeData
* @return {Uint8Array<Number>} dataArr - array with sound frequency data
*/
Phaser.SoundAnalyser.prototype.getFakeData = function () {
var res = [];
for (var k = 0; k < this._bufferLength; ++k) {
res.push(Math.abs(this.game.rnd.integerInRange(this._minDecibels, this._maxDecibels)));
}
res.sort(function(a, b){return b-a});
return res;
};
/**
* Get re-sampled (average) audio data
*
* @static
* @method Phaser.AudioSprite#getAvgData
* @param {Uint8Array<Number>} dataArr - array with sound frequency data
* @param {number} - bufferLength - the size of the frequency data
* @param {number} - resultSlots - number of result slots you want
* @param {number} - maxMinValue - input minimal value used for calculating data
* @param {number} - outMaxValue - maximum result value for every frequency data
* @return {Uint8Array<Number>} dataArr - array with re-sampled (averaged) sound frequency data
*/
Phaser.SoundAnalyser.getAvgData = function (dataArray, bufferLength, resultSlots, maxMinValue, outMaxValue) {
normalizeValue = normalizeValue || 256;
var value, percent, height, offset, barWidth, hue, avg;
var res = [];
if (bufferLength == resultSlots) {
barWidth = this.width / bufferLength;
for (var i = 0; i < bufferLength; i++) {
value = dataArray[i];
percent = value / maxMinValue;
size = Math.floor(outMaxValue * percent, 10);
res.push(size);
}
} else {
var destBars = resultSlots;
var destPart = Math.round(bufferLength / destBars);
barWidth = this.width / destBars;
var i = 0;
for (var x = 0; x < destBars; x++) {
avg = 0;
for (var k = 0; k < destPart; ++k, ++i) {
if (i >= bufferLength) { break; }
avg += dataArray[i];
}
avg = Math.floor(avg / destPart, 10);
value = avg;
percent = value / maxMinValue;
size = Math.floor(outMaxValue * percent, 10);
res.push(size);
if (i >= bufferLength) { break; }
}
if (i < bufferLength) {
x++;
avg = 0;
for (; i < bufferLength; ++i) {
avg += dataArray[i];
}
avg = Math.floor(avg / destPart, 10);
value = avg;
percent = value / maxMinValue;
size = Math.floor(outMaxValue * percent, 10);
res.push(size);
}
}
return res;
};
/**
* iterate and callback for every re-sampled (averaged) slot data
*
* @static
* @method Phaser.AudioSprite#eachAvgData
* @param {Uint8Array<Number>} dataArr - array with sound frequency data
* @param {number} - bufferLength - the size of the frequency data
* @param {number} - resultSlots - number of result slots you want
* @param {number} - maxMinValue - input minimal value used for calculating data
* @param {number} - outMaxValue - maximum result value for every frequency data
* @param {Function} - callback - callback function
* @param {context} - callback - context to be provided in callback function
* @return {Uint8Array<Number>} dataArr - array with re-sampled (averaged) sound frequency data
*/
Phaser.SoundAnalyser.eachAvgData = function (dataArray, bufferLength, resultSlots, maxMinValue, outMaxValue, callback, context) {
maxMinValue = maxMinValue || 256;
outMaxValue = outMaxValue || maxMinValue;
var value, percent, height, offset, barWidth, hue, avg;
var res = [];
if (bufferLength == resultSlots) {
barWidth = this.width / bufferLength;
for (var i = 0; i < bufferLength; i++) {
value = dataArray[i];
percent = value / maxMinValue;
size = Math.floor(outMaxValue * percent, 10);
if (callback) {
callback.call(context, size, percent, i, i);
}
}
} else {
var destBars = resultSlots;
var destPart = Math.round(bufferLength / destBars);
barWidth = this.width / destBars;
var i = 0;
for (var x = 0; x < destBars; x++) {
avg = 0;
for (var k = 0; k < destPart; ++k, ++i) {
if (i >= bufferLength) { break; }
avg += dataArray[i];
}
avg = Math.floor(avg / destPart, 10);
value = avg;
percent = value / maxMinValue;
size = Math.floor(outMaxValue * percent, 10);
if (callback) {
callback.call(context, size, percent, x, i);
}
if (i >= bufferLength) { break; }
}
if (i < bufferLength) {
x++;
avg = 0;
for (; i < bufferLength; ++i) {
avg += dataArray[i];
}
avg = Math.floor(avg / destPart, 10);
value = avg;
percent = value / maxMinValue;
size = Math.floor(outMaxValue * percent, 10);
if (callback) {
callback.call(context, size, percent, x, i);
}
}
}
return res;
};
/** --- BITMAP DATA SOUND ANALYSE --- **/
/**
* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
* A single BitmapData can be used as the texture for one or many Images/Sprites.
* So if you need to dynamically create a Sprite texture then they are a good choice.
*
* We use this BitmapData to draw our audio analyse data
*
* @class Phaser.BitmapDataSoundAnalyze
* @extends Phaser.BitmapData
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {string} key - Internal Phaser reference key for the BitmapData.
* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value.
* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value.
* @param {Phaser.SoundAnalyser} [soundAnalyser=null] - The SoundAnalyser object that will provide data to this bitmap
*/
Phaser.BitmapDataSoundAnalyze = function (game, key, width, height, soundAnalyser) {
// call base object constructor
Phaser.BitmapData.call(this, game, key, width, height);
/**
* @property {Number|def:1024} frequencyDomainChartBars - Number of bars to be drawn
*/
this.frequencyDomainChartBars = 1024;
/**
* @property {Boolean} drawFrequencyDomainChart - If true it will draw frequency domain chart (vertical sound bars)
*/
this.drawFrequencyDomainChart = true;
/**
* @property {Boolean} drawTimeDomainChart - If true it will draw frequency time domain chart (horizontal sound line)
*/
this.drawTimeDomainChart = false;
/**
* @property {Boolean} drawFrequencyDomainChartUniform - If true it will draw frequency time domain chart in uniformed distribution of the magnitude
*/
this.drawFrequencyDomainChartUniform = false;
/**
* @property {Boolean} drawFrequencyDomainChartUniformMirror - If true it will draw frequency time domain chart in uniformed distribution of the magnitude with mirror effect
*/
this.drawFrequencyDomainChartUniformMirror = false;
/**
* @property {Boolean} drawTimeDomainChart - If true it will draw volume meter bar
*/
this.drawVolumeMetar = false;
/**
* @property {Boolean} drawVolumeMetarLeftRight - If true it will draw two stereo volume meter bars
*/
this.drawVolumeMetarLeftRight = false;
/**
* @property {Boolean} drawBackgroundVolume - If true it will draw background volume meter gradient
*/
this.drawBackgroundVolume = false;
/**
* @property {Boolean} drawBackgroundData - If true it will draw background meter gradient with data interpolated into colors provided (number of colors will represent number of data/gradient step)
*/
this.drawBackgroundData = false;
/**
* @property {Object} backgroundVolumeColorRange - minimum color object for background amplitude animation
* Object structure (example):
* {
* color: { hex: "#ee3a3a", r: 238, g: 58, b: 58 },
* min: { hex: "#F21313", r: 242, g: 19, b: 19 },
* max: { hex: "#DB5A5A", r: 219, g: 90, b: 90 }
* }
*/
this.backgroundVolumeColorRange = {
color: { hex: "#B0E4F5", r: 176, g: 228, b: 245 },
min: { hex: "#C2F5B0", r: 195, g: 245, b: 176 },
max: { hex: "#E3B0F5", r: 227, g: 176, b: 245 },
};
/**
* @property {Array<Object>} backgroundDataColorRange - array of color objects that will represent audio data
* Object structure (example):
* {
* color: { hex: "#ee3a3a", r: 238, g: 58, b: 58 },
* min: { hex: "#F21313", r: 242, g: 19, b: 19 },
* max: { hex: "#DB5A5A", r: 219, g: 90, b: 90 }
* }
*/
this.backgroundDataColorRange = [
{
color: { hex: "#30d2b9", r: 48, g: 210, b: 185 },
min: { hex: "#02F7D2", r: 2, g: 247, b: 210 },
max: { hex: "#53968C", r: 83, g: 150, b: 140 },
},
{
color: { hex: "#ee3a3a", r: 238, g: 58, b: 58 },
min: { hex: "#F21313", r: 242, g: 19, b: 19 },
max: { hex: "#DB5A5A", r: 219, g: 90, b: 90 },
},
{
color: { hex: "#793aee", r: 121, g: 58, b: 238 },
min: { hex: "#6011F2", r: 96, g: 17, b: 242 },
max: { hex: "#966EE0", r: 150, g: 110, b: 224 },
},
{
color: { hex: "#30d2b9", r: 48, g: 210, b: 185 },
min: { hex: "#02F7D2", r: 2, g: 247, b: 210 },
max: { hex: "#53968C", r: 83, g: 150, b: 140 },
},
];
/**
* @property {Number} backgroundAlpha - alpha value for background in range from 0 to 1
*/
this.backgroundAlpha = 1;
/**
* @property {Number} backgroundAlpha - alpha value for background in range from 0 to 1
*/
this.backgroundTweening = null;
/**
* @property {String|Hex} timeChartColor - color for time domain chart (you can use any web supported format)
*/
this.timeChartColor = "#0000ff";
/**
* @property {String|Hex} volumeMetarColor - color for the volume meter
*/
this.volumeMetarColor = "#FFAA00";
/**
* @property {String|Hex} volumeMetarLeftColor - color for the left volume meter
*/
this.volumeMetarLeftColor = "#FFAA00";
/**
* @property {String|Hex} volumeMetarRightColor - color for the right volume meter
*/
this.volumeMetarRightColor = "#FFAA33";
/**
* @property {String|Hex} [frequencyDomainChartUniformColor="#FFAA33"] - color for the frequency domain chart uniform
*/
this.frequencyDomainChartUniformColor = "#FFAA33";
// set reference to sound analyser object
this.soundAnalyser = soundAnalyser;
// add sound analyse bitmap to sound analyse object if provided
if (this.soundAnalyser) {
this.soundAnalyser.addBitmapSoundAnalyse(this);
}
};
// constructor setup
Phaser.BitmapDataSoundAnalyze.prototype = Object.create(Phaser.BitmapData.prototype);
Phaser.BitmapDataSoundAnalyze.prototype.constructor = Phaser.BitmapDataSoundAnalyze;
/**
* Called automatically by Phaser.BitmapDataSoundAnalyze. to get transformed value
*
* @method Phaser.BitmapDataSoundAnalyze#linearCut
* @property {Number} inVal - value we want to transform
* @property {Number} inMin - minimum input range for the inVal
* @property {Number} inMax - maximum input range for the inVal
* @property {Number} inMin - minimum output range for the inVal
* @property {Number} inMax - maximum output range for the inVal
* @return {Number} return inVal number in range [outMin..outMax]
*/
Phaser.BitmapDataSoundAnalyze.prototype.linearCut = function (inVal, inMin, inMax, outMin, outMax) {
var res = (inVal - inMin) / (inMax - inMin) * (outMax - outMin) + outMin;
if (res < outMin) {
res = outMin
} else if (res > outMax) {
res = outMax;
}
return Math.floor(res);
};
/**
* Method to tween bitmap sound analyse background from current background color to the one provided
*
* @method Phaser.BitmapDataSoundAnalyze#linearCut
* @property {Number} endColorVal - tint color values
* @property {Number} time - animation time duration in milliseconds
* @property {Function} callBack - method to be called on finish animation
* @property {Object} context - context object to be provided in callback method
* @return {Phaser.BitmapDataSoundAnalyze} return self reference
*/
Phaser.BitmapDataSoundAnalyze.prototype.tweenBackground = function (endColorVal, time, callBack, context) {
if (this.backgroundTweening) {
this.backgroundTweening.stop();
this.game.tweens.remove(this.backgroundTweening);
}
this.backgroundTweening = null;
var self = this;
var startColor = Phaser.Color.getColor32(this.backgroundAlpha, this.backgroundVolumeColorRange.color.r,
this.backgroundVolumeColorRange.color.g, this.backgroundVolumeColorRange.color.b);
this.backgroundVolumeColorRange = endColorVal;
var endColor = Phaser.Color.getColor32(this.backgroundAlpha, endColorVal.color.r,
endColorVal.color.g, endColorVal.color.b);
// create an object to tween with our step value at 0
var colorBlend = {step: 0};
// create the tween on this object and tween its step property to 100
this.backgroundTweening = this.game.add.tween(colorBlend).to({step: 100}, time);
// run the interpolateColor function every time the tween updates, feeding it the
// updated value of our tween each time, and set the result as our tint
this.backgroundTweening.onUpdateCallback(function() {
var col = Phaser.Color.valueToColor(Phaser.Color.interpolateColor(startColor, endColor, 100, colorBlend.step));
self.clear();
self.ctx.save();
self.ctx.fillStyle = "rgba(" + col.r + ", " + col.g + ", " +
col.b + ", " + self.backgroundAlpha + ")";
self.ctx.fillRect(0, 0, self.width, self.height);
self.ctx.restore();
});
this.backgroundTweening.onComplete.addOnce(function () {
self.clear();
self.ctx.save();
self.ctx.fillStyle = "rgba(" + endColorVal.color.r + ", " + endColorVal.color.g + ", " +
endColorVal.color.b + ", " + self.backgroundAlpha + ")";
self.ctx.fillRect(0, 0, self.width, self.height);
self.ctx.restore();
self.game.tweens.remove(self.backgroundTweening);
self.backgroundTweening = null;
if (callBack) { callBack.call(context); }
}, this);
// start the tween
this.backgroundTweening.start();
return this;
};
/**
* Method called to update it draw state every time we have new analyse data
*
* @method Phaser.BitmapDataSoundAnalyze#linearCut
* @param {Uint8Array<Number>} dataArr - array with sound frequency data
* @param {Uint8Array<Number>} dataTimeArray - array with sound time frequency data
* @param {number} - bufferLength - the size of the frequency data
* @param {number} - volumeMeter - sound volume meter value
* @param {number} - volumeMeterLeft - sound volume meter value for the left stereo sound
* @param {number} - volumeMeterRight - sound volume meter value for the right stereo sound
* @return {Phaser.BitmapDataSoundAnalyze} return self reference
* @protected
*/
Phaser.BitmapDataSoundAnalyze.prototype.updateAnalyse = function (dataArray, dataTimeArray, bufferLength, volumeMeter, volumeMeterLeft, volumeMeterRight) {
this.clear();
if (this.backgroundVolumeColorRange && this.backgroundVolumeColorRange["color"]) {
this.ctx.save();
this.ctx.fillStyle = "rgba(" + this.backgroundVolumeColorRange["color"].r + ", " +
this.backgroundVolumeColorRange["color"].g + ", " + this.backgroundVolumeColorRange["color"].b +
", " + this.backgroundAlpha + ")";
this.ctx.fillRect(0, 0, this.width, this.height);
this.ctx.restore();
}
if (!dataArray && !dataTimeArray && !bufferLength && !volumeMeter && !volumeMeterLeft && !volumeMeterRight) {
return this;
}
var width = Math.floor(1 / bufferLength, 10);
var value, percent, height, offset, barWidth, hue, avg;
if (this.drawBackgroundVolume && this.backgroundVolumeColorRange["min"] && this.backgroundVolumeColorRange["max"]) {
this.ctx.save();
var grd = this.ctx.createLinearGradient(0, 0, this.width, 0);
var minR = Math.min(this.backgroundVolumeColorRange["min"].r, this.backgroundVolumeColorRange["max"].r);
var maxR = Math.max(this.backgroundVolumeColorRange["min"].r, this.backgroundVolumeColorRange["max"].r);
var minG = Math.min(this.backgroundVolumeColorRange["min"].g, this.backgroundVolumeColorRange["max"].g);
var maxG = Math.max(this.backgroundVolumeColorRange["min"].g, this.backgroundVolumeColorRange["max"].g);
var minB = Math.min(this.backgroundVolumeColorRange["min"].b, this.backgroundVolumeColorRange["max"].b);
var maxB = Math.max(this.backgroundVolumeColorRange["min"].b, this.backgroundVolumeColorRange["max"].b);
var r, g, b;
percent = volumeMeterLeft / 256;
height = Math.floor(255 * percent, 10);
r = this.linearCut(height, 0, 255, minR, maxR);
g = this.linearCut(height, 0, 255, minG, maxG);
b = this.linearCut(height, 0, 255, minB, maxB);
grd.addColorStop(0, "rgba(" + r + ", " + g + ", " + b + ", " + this.backgroundAlpha + ")");
percent = volumeMeter / 256;
height = Math.floor(255 * percent, 10);
r = this.linearCut(height, 0, 255, minR, maxR);
g = this.linearCut(height, 0, 255, minG, maxG);
b = this.linearCut(height, 0, 255, minB, maxB);
grd.addColorStop(0, "rgba(" + r + ", " + g + ", " + b + ", " + this.backgroundAlpha + ")");
percent = volumeMeterRight / 256;
height = Math.floor(255 * percent, 10);
r = this.linearCut(height, 0, 255, minR, maxR);
g = this.linearCut(height, 0, 255, minG, maxG);
b = this.linearCut(height, 0, 255, minB, maxB);
grd.addColorStop(0, "rgba(" + r + ", " + g + ", " + b + ", " + this.backgroundAlpha + ")");
this.ctx.fillStyle = grd;
this.ctx.fillRect(0, 0, this.width, this.height);
this.ctx.restore();
} else if (this.drawBackgroundData) {
var minR, maxR, minG, maxG, minB, maxB, r, g, b, colorData;
var grd = this.ctx.createLinearGradient(0, 0, this.width, 0);
var steps = this.backgroundDataColorRange.length;
this.ctx.save();
Phaser.SoundAnalyser.eachAvgData(dataArray, bufferLength, steps, 255, 255,
function (size, percent, indexBar, globalIndex) {
if (indexBar >= steps) return;
colorData = this.backgroundDataColorRange[indexBar];
minR = Math.min((colorData["min"].r || 0), (colorData["max"].r || 255));
maxR = Math.max((colorData["min"].r || 0), (colorData["max"].r || 255));
minG = Math.min((colorData["min"].g || 0), (colorData["max"].g || 255));
maxG = Math.max((colorData["min"].g || 0), (colorData["max"].g || 255));
minB = Math.min((colorData["min"].b || 0), (colorData["max"].b || 255));
maxB = Math.max((colorData["min"].b || 0), (colorData["max"].b || 255));
r = this.linearCut(size, 0, 255, minR, maxR);
g = this.linearCut(size, 0, 255, minG, maxG);
b = this.linearCut(size, 0, 255, minB, maxB);
step = indexBar / steps;
grd.addColorStop(step, "rgba(" + r + ", " + g + ", " + b + ", " + this.backgroundAlpha + ")");
},
this);
this.ctx.fillStyle = grd;
this.ctx.fillRect(0, 0, this.width, this.height);
this.ctx.restore();
}
if (this.drawFrequencyDomainChart) {
this.ctx.save();
if (this.frequencyChartColor) {
this.ctx.fillStyle = this.frequencyChartColor;
}
var height, offset, hue;
var destBars = this.frequencyDomainChartBars;
var destPart = Math.round(bufferLength / destBars);
barWidth = this.width / destBars;
Phaser.SoundAnalyser.eachAvgData(dataArray, bufferLength, this.frequencyDomainChartBars, 256, this.height,
function (size, percent, indexBar, globalIndex) {
height = this.height * percent;
offset = this.height - height - 1;
if (!this.frequencyChartColor) {
hue = indexBar / destBars * 360;
this.ctx.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
}
this.ctx.fillRect(indexBar * barWidth, offset, barWidth, height);
},
this);
this.ctx.restore();
}
if (this.drawFrequencyDomainChartUniform) {
var SPACER_WIDTH = 10;
var BAR_WIDTH = 5;
var OFFSET = Math.round(this.height / 3);
var CUTOFF = 23;
var numBars = Math.round(this.width / SPACER_WIDTH);
this.ctx.save();
this.ctx.lineCap = 'round';
for (var i = 1; i < numBars-1; ++i) {
var magnitude;
if (this.height < 300) {
magnitude = this.height - dataArray[i + OFFSET];
} else {
magnitude = dataArray[i + OFFSET];
}
this.ctx.fillStyle = this.frequencyDomainChartUniformColor;
if (this.drawFrequencyDomainChartUniformMirror) {
if (this.height < 150) {
this.ctx.globalAlpha = 1;
this.ctx.fillRect(i * SPACER_WIDTH, this.height / 2, BAR_WIDTH, magnitude);
this.ctx.globalAlpha = 0.5;
this.ctx.fillRect(i * SPACER_WIDTH, this.height / 2, BAR_WIDTH, -magnitude);
} else {
this.ctx.globalAlpha = 1;
this.ctx.fillRect(i * SPACER_WIDTH, this.height / 2, BAR_WIDTH, -magnitude);
this.ctx.globalAlpha = 0.5;
this.ctx.fillRect(i * SPACER_WIDTH, this.height / 2, BAR_WIDTH, magnitude);
}
} else {
this.ctx.fillRect(i * SPACER_WIDTH, this.height / 2 + magnitude / 2, BAR_WIDTH, -magnitude);
}
}
this.ctx.restore();
}
if (this.drawTimeDomainChart) {
this.ctx.save();
this.ctx.strokeStyle = this.timeChartColor;
this.ctx.lineWidth = 2;
this.ctx.beginPath();
for (var i = 0; i < bufferLength; i++) {
value = dataTimeArray[i];
percent = value / 256;
height = (this.height * percent) / 2;
offset = 2 * height;
barWidth = this.width / bufferLength;
if(i === 0) {
this.ctx.moveTo(i * barWidth, offset);
} else {
this.ctx.lineTo(i * barWidth, offset);
}
}
this.ctx.lineTo(this.width, this.height / 2);
this.ctx.stroke();
this.ctx.restore();
}
if (this.drawVolumeMetar) {
this.ctx.save();
this.ctx.fillStyle = this.volumeMetarColor;
width = 20;
percent = volumeMeter / 256;
height = this.height * percent;
this.ctx.fillRect(this.width/2-width/2, this.height-height, width, height);
this.ctx.restore();
}
if (this.drawVolumeMetarLeftRight) {
this.ctx.save();
width = 20; offset = 30 + width;
this.ctx.fillStyle = this.volumeMetarLeftColor;
percent = volumeMeterLeft / 256;
height = this.height * percent;
this.ctx.fillRect(this.width/2-width/2-offset, this.height-height, width, height);
this.ctx.fillStyle = this.volumeMetarRightColor;
percent = volumeMeterRight / 256;
height = this.height * percent;
this.ctx.fillRect(this.width/2-width/2, this.height-height, width, height);
this.ctx.restore();
}
return this;
};
/**
* Sprites are the lifeblood of your game, used for nearly everything visual.
*
* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
*
* This sprite will hold our visual sound analyse data object, it will represent visual texture and will
* hold direct link to some audio analyse properties
*
* @class Phaser.SoundAnalyseSprite
* @extends Phaser.Sprite
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
* @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
* @param {number} [width=game.width] - The width of the sprite
* @param {number} [height=game.height] - The height of the sprite
* @param {number} songKey - The key value for the song
* @param {Boolean} autoPlay - if true song will start playing automatically
* @param {Function} onDecodeComplete - method callback on sound decoding complete
* @param {Object} context - context object to be provided in callback method
* @param {Phaser.group} group - group object to add this sprite
*/
Phaser.SoundAnalyseSprite = function (game, x, y, width, height, songKey, autoPlay, onDecodeComplete, context, group) {
width = width || game.width;
height = height || game.height;
// create sound analyse object
this.songAnalyse = new Phaser.SoundAnalyser(game, songKey, 1, false);
game.sound._sounds.push(this.songAnalyse);
// bitmap analyse texture
this.bmpAnalyseTexture = new Phaser.BitmapDataSoundAnalyze(game, game.rnd.uuid(), width, height, this.songAnalyse);
// We call the Phaser.Sprite passing in the game reference
Phaser.Sprite.call(this, game, x, y, this.bmpAnalyseTexture);
// add sprite to game word
if (group) {
group.add(this);
} else {
game.add.existing(this);
}
// if auto play is true, then start the song
if (autoPlay === true) {
this.songAnalyse.play();
}
this.songAnalyse.onDecoded.addOnce(function () {
// call provided callback method
if (onDecodeComplete) {
onDecodeComplete.call(context, this);
}
}, this);