-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinterval-timer.js
1429 lines (1244 loc) · 48.1 KB
/
interval-timer.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
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_RESULT__;
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
var audio = {};
(function(samplerate){
this.SampleRate = samplerate || 44100;
var SampleRate = this.SampleRate;
// Do not modify parameters without changing code!
var BitsPerSample = 16;
var NumChannels = 1;
var BlockAlign = NumChannels * BitsPerSample >> 3;
var ByteRate = SampleRate * BlockAlign;
// helper functions
var chr = String.fromCharCode; // alias for getting converting int to char
//////////////////////
// Wave ///
//////////////////////
var waveTag="data:audio/wav;base64,";
// constructs a wave from sample array
var constructWave = function(data){
var l;
return pack( ["RIFF",36+(l=data.length),"WAVEfmt ",16,1,NumChannels,SampleRate,
ByteRate,BlockAlign,BitsPerSample,"data",l,data],"s4s4224422s4s");
};
// creates an audio object from sample data
this.make = function(arr){
return new Audio(waveTag + btoa(constructWave(arrayToData(arr))))
};
// creates a wave file for downloading
this.makeWaveFile = function(arr){
dataToFile(waveTag + btoa(constructWave(arrayToData(arr))))
};
this.makeAudioBuffer = function(ctx, data) {
var buffer = ctx.createBuffer(1, data.length, SampleRate);
var array = buffer.getChannelData(0);
for (var i = 0; i < data.length; ++i) {
array[i] = data[i];
}
return buffer;
};
//////////////////////
// General stuff ///
//////////////////////
// Converts an integer to String representation
// a - number
// i - number of bytes
var istr = function(a,i){
var m8 = 0xff; // 8 bit mask
return i?chr(a&m8)+istr(a>>8,i-1):"";
};
// Packs array of data to a string
// data - array
// format - s is for string, numbers denote bytes to store in
var pack = function(data,format){
var out="";
for(i=0;i<data.length;i++)
out+=format[i]=="s"?data[i]:istr(data[i],format.charCodeAt(i)-48);
return out;
}
var dataToFile = function(data){
document.location.href = data;
}
//////////////////////
// Audio Processing ///
//////////////////////
// Utilities
//////////////////////
// often used variables (just for convenience)
var count,out,i,sfreq;
var sin = Math.sin;
var TAU = 2*Math.PI;
var Arr = function(c){return new Array(c|0)}; // alias for creating a new array
var clamp8bit = function(a){return a<0?0:255<a?255:a}
var sample8bit = function(a){return clamp((a*127+127)|0)}
this.toTime = function(a){return a/SampleRate}
this.toSamples = function(a){return a*SampleRate}
var arrayToData16bit = function(arr){
var out="";
var len = arr.length;
for( i=0 ; i < len ; i++){
var a = (arr[i] * 32767) | 0;
a = a < -32768 ? -32768 : 32767 < a ? 32767 : a; // clamp
a += a < 0 ? 65536 : 0; // 2-s complement
out += String.fromCharCode(a & 255, a >> 8);
};
return out;
}
var arrayToData8bit = function(arr){
var out="";
var len = arr.length;
for( i=0 ; i < len ; i++){
var a = (arr[i] * 127 + 128) | 0;
a = a < 0 ? 0 : 255 < a ? 255 : a;
out += String.fromCharCode(a);
};
return out;
}
var arrayToData = function(arr){
if( BitsPerSample == 16 )
return arrayToData16bit(arr);
else
return arrayToData8bit(arr);
}
//////////////////////
// Processing
//////////////////////
// adjusts volume of a buffer
this.adjustVolume = function(data, v){
for(i=0;i<data.length;i++)
data[i] *= v;
return data;
}
// Filters
//////////////////////
this.filter = function(data,func,from,to,A,B,C,D,E,F){
from = from ? from : 1;
to = to ? to : data.length;
out = data.slice(0);
for(i=from;i<to;i++)
out[i] = func(data, out, from,to,i,A,B,C,D,E,F)
return out;
};
var filter = this.filter;
this.filters = {
lowpass :
function(data, out, from, to, pos, A){
return out[pos-1] + A * (data[pos] - out[pos-1]);
},
lowpassx :
function(data, out, from, to, pos, A){
return out[pos-1] + A*(to - pos)/(to-from) * (data[pos] - out[pos-1]);
},
highpass :
function(data, out, from, to, pos, A){
return A * (out[pos-1] + data[pos] - data[pos-1])
}
};
var filters = this.filters;
this.f = {
lowpass : function(data, from, to, A){return filter(data, filters.lowpass, from, to, A);},
lowpassx : function(data, from, to, A){return filter(data, filters.lowpassx, from, to, A);},
highpass : function(data, from, to, A){return filter(data, filters.highpass, from, to, A);}
}
// Generators
//////////////////////
// general sound generation
// example:
// generate(3, 440, Math.sin);
this.generate = function(count, freq, func, A, B, C, D, E, F){
var sfreq=freq*TAU/SampleRate;
var out = Arr(count);
for(i=0; i < count;i++)
out[i] = func(i*sfreq,A,B,C,D,E,F);
return out;
}
var lastNoise = 0;
var generate = this.generate;
this.generators = {
noise : function(phase){
if(phase % TAU < 4){
lastNoise = Math.random() * 2 - 1;
}
return lastNoise;
},
uninoise : Math.random,
sine : Math.sin,
synth : function(phase){return sin(phase) + .5*sin(phase/2) + .3*sin(phase/4)},
saw : function(phase){return 2*(phase/TAU - ((phase/TAU + 0.5)|0))},
square : function(phase,A){return sin(phase) > A ? 1.0 : sin(phase) < A ? -1.0 : A}
};
var generators = this.generators;
this.g = {
noise : function(count){ return generate(count,0, generators.noise) },
sine : function(count, freq){ return generate(count, freq, generators.sine) },
synth : function(count, freq){ return generate(count, freq, generators.synth) },
saw : function(count, freq){ return generate(count, freq, generators.saw) },
square : function(count, freq, A){ return generate(count, freq, generators.square, A) }
};
}).apply(audio);
return audio;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(2),
], __WEBPACK_AMD_DEFINE_RESULT__ = (function (
AudioManager
) {
window.AudioManager = AudioManager;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(3),
__webpack_require__(5)
], __WEBPACK_AMD_DEFINE_RESULT__ = (function(
jsfxlib,
EventEmitter) {
var webAudioAPI = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
/**
* @typedef {Object} AudioManager~Options
* @property {callback} startedOnTouchCallback: **DEPREICATED**
* Use `mgr.on(`started`)
*
* @property {callback} callback: **DEPRECATED** use
* mgr.on('loaded').
*/
/**
* This can either be a path to a file OR jsfx data for sounds
* generated at runtime. Example:
*
* var sounds = {
* coin: { jsfx: ["square",0.0000,0.4000,0.0000,0.0240,0.4080,0.3480,20.0000,909.0000,2400.0000,0.0000,0.0000,0.0000,0.0100,0.0003,0.0000,0.2540,0.1090,0.0000,0.0000,0.0000,0.0000,0.0000,1.0000,0.0000,0.0000,0.0000,0.0000], },
* jump: { jsfx: ["square",0.0000,0.4000,0.0000,0.0960,0.0000,0.1720,20.0000,245.0000,2400.0000,0.3500,0.0000,0.0000,0.0100,0.0003,0.0000,0.0000,0.0000,0.5000,0.0000,0.0000,0.0000,0.0000,1.0000,0.0000,0.0000,0.0000,0.0000], },
* fire: { filename: "assets/fire.ogg", samples: 8, },
* boom: { filename: "assets/explosion.ogg", samples: 8, },
* };
*
*
* Note Firefox doesn't support MP3s as far as I know so you'll need
* to supply .ogg files for it. Conversely, Safari doesn't support .ogg.
* The library handles loading .mp3 or .ogg files regardless of what you specify
* when you init the library. In other words if you put `filename: "foo.mp3"`
* the library will try to load `foo.mp3` or `foo.ogg` depending on if the
* browser supports one or the other.
*
* @typedef {Object} AudioManager~Sound
* @property {string?} filename path to the file to load
* @property {number?} samples How many of this sound can play
* simultainously. Note: this is NOT needed when using
* the Web Audio API. It is only needed for legacy
* browsers like IE11 and below.
* @property {Array?} jsfx Data from jsfx. See http://egonelbre.com/project/jsfx/
*/
/**
* To use this include it with
*
* <script src="audio.js"></script>
*
* Then give it a list of sounds like this
*
* var audioMgr = new AudioManager({
* fire: { filename: "assets/fire.ogg", samples: 8, },
* explosion: { filename: "assets/explosion.ogg", samples: 6, },
* hitshield: { filename: "assets/hitshield.ogg", samples: 6, },
* launch: { filename: "assets/launch.ogg", samples: 2, },
* gameover: { filename: "assets/gameover.ogg", samples: 1, },
* play: { filename: "assets/play.ogg", samples: 1, },
* });
*
* After that you can play sounds with
*
* audioMgr.playSound('explosion');
* audioMgr.playSound('fire');
*
* The signature for `playSound` is
* `playSound(name, when, loop)` where when is the time to play
* the sound and loop is whether or not to play the sound
* continuously in a loop.
*
* Playsound returns an object you can use to control the sound
* though this part of the API is still in flux.
*
* `samples` is how may of that sound you want to be able to play at
* the same time. THIS IS NOT NEEDED for any browser that supports the
* Web Audio API. In other words it's only needed for IE.
*
* Also note Firefox doesn't support MP3s as far as I know so you'll need
* to supply .ogg files for it. Conversely, Safari doesn't support .ogg.
* The library handles loading .mp3 or .ogg files regardless of what you specify
* when you init the library. In other words if you put `filename: "foo.mp3"`
* the library will try to load `foo.mp3` or `foo.ogg` depending on if the
* browser supports one or the other.
*
* @constructor
* @param {Object(string:AudioManager~Sound}} sounds The sounds
* to load
* @param {AudioManager~Options} options Options
* @fires AudioManager#loaded when all sounds have loaded
* @fires AudioManager#started when the first sound has played.
* On iOS no sounds can be played unless at least one is
* first initiated during a use gesture event. This event
* is useful for situtations where sounds 'should' start
* right from the beginning even if the player as not
* touched the screen. For exampme we might put up a
* message, "touch the screen" and remove that message
* when we get this event
*/
var AudioManager = function(sounds, options) {
options = options || {};
var g_eventEmitter = new EventEmitter();
var g_context;
var g_audioMgr;
var g_soundBank = {};
var g_canPlay = false;
var g_canPlayOgg;
var g_canPlayMp3;
var g_canPlayWav;
var g_canPlayAif;
var g_createFromFileFn;
var g_createFromJSFXFn;
var changeExt = function(filename, ext) {
return filename.substring(0, filename.length - 3) + ext;
};
this.needUserGesture = function() {
return true;
};
this.on = g_eventEmitter.on.bind(g_eventEmitter);
this.addListener = this.on;
this.addEventListener = this.on;
this.removeListener = g_eventEmitter.removeListener.bind(g_eventEmitter);
this.removeEventListener = this.removeListener;
if (options.callback) {
console.warn("AudioManager: options.callback is deprecated. Use mgr.on('loaded', ...)");
this.on('loaded', options.callback);
}
if (options.startedOnTouchCallback) {
console.warn("AudioManager: options.startedOnTouchCallback is deprecated. Use mgr.on('started', ...)");
this.on('started', options.callback);
}
var WebAudioBuffer = function() {
};
WebAudioBuffer.prototype.play = function(opt_when, opt_loop) {
if (!this.buffer) {
console.log(this.name, " not loaded");
return;
}
var src = g_context.createBufferSource();
src.buffer = this.buffer;
src.loop = opt_loop || false;
src.connect(g_context.destination);
if (src.start) {
src.start(opt_when || 0);
} else {
src.noteOn(opt_when || 0);
}
return src;
};
var WebAudioJSFX = function(name, data, samples, opt_callback) {
this.buffer = jsfxlib.createAudioBuffer(g_context, data);
if (opt_callback) {
setTimeout(opt_callback, 0);
}
};
WebAudioJSFX.prototype = new WebAudioBuffer();
function WebAudioSound(name, filename, samples, opt_callback) {
this.name = name;
var that = this;
var req = new XMLHttpRequest();
req.open("GET", filename, true);
req.responseType = "arraybuffer";
req.onload = function() {
g_context.decodeAudioData(req.response, function onSuccess(decodedBuffer) {
// Decoding was successful, do something useful with the audio buffer
that.buffer = decodedBuffer;
if (opt_callback) {
opt_callback(false);
}
}, function onFailure() {
console.error("failed to decoding audio buffer: " + filename);
if (opt_callback) {
opt_callback(true);
}
});
}
req.addEventListener("error", function(e) {
console.error("failed to load:", filename, " : ", e.target.status);
}, false);
req.send();
}
WebAudioSound.prototype = new WebAudioBuffer();
var AudioTagJSFX = function(name, data, samples, opt_callback) {
this.samples = samples || 1;
this.audio = {};
this.playNdx = 0;
for (var i = 0; i < samples; ++i) {
this.audio[i] = jsfxlib.createWave(data);
}
if (opt_callback) {
setTimeout(opt_callback, 0);
}
};
AudioTagJSFX.prototype.play = function(opt_when, opt_loop) {
this.playNdx = (this.playNdx + 1) % this.samples;
var a = this.audio[this.playNdx];
var b = new Audio();
b.src = a.src;
// TODO: use when
b.addEventListener("canplaythrough", function() {
b.play();
}, false);
b.load();
};
function AudioTagSound(name, filename, samples, opt_callback) {
this.waiting_on_load = samples;
this.samples = samples || 1;
this.name = name;
this.play_idx = 0;
this.audio = {};
for (var i = 0; i < samples; i++) {
var audio = new Audio();
var that = this;
var checkCallback = function(err) {
that.waiting_on_load--;
if (opt_callback) {
opt_callback(err);
}
};
audio.addEventListener("canplaythrough", function() {
checkCallback(false);
}, false);
audio.src = filename;
audio.onerror = function() {
checkCallback(true);
};
audio.load();
this.audio[i] = audio;
}
};
AudioTagSound.prototype.play = function(opt_when, opt_loop) {
if (this.waiting_on_load > 0) {
console.log(this.name, " not loaded");
return;
}
this.play_idx = (this.play_idx + 1) % this.samples;
var a = this.audio[this.play_idx];
// console.log(this.name, ":", this.play_idx, ":", a.src);
var b = new Audio();
b.src = a.src;
// TODO: use when
b.addEventListener("canplaythrough", function() {
b.play();
}, false);
b.load();
};
var handleError = function(filename, audio) {
return function(e) {
console.error("can't load ", filename);
}
};
this.playSound = function(name, opt_when, opt_loop) {
if (!g_canPlay)
return;
var sound = g_soundBank[name];
if (!sound) {
console.error("audio: '" + name + "' not known.");
return;
}
return sound.play(opt_when, opt_loop);
}.bind(this);
this.getTime = function() {
return g_context ? g_context.currentTime : Date.now() * 0.001;
}.bind(this);
// on iOS and possibly other devices you can't play any
// sounds in the browser unless you first play a sound
// in response to a user gesture. So, make something
// to respond to a user gesture.
var setupGesture = function() {
if (this.needUserGesture()) {
var count = 0;
var elem = window;
var that = this;
var eventNames = ['touchstart', 'mousedown'];
var playSoundToStartAudio = function() {
++count;
if (count < 3) {
// just playing any sound does not seem to work.
var source = g_context.createOscillator();
var gain = g_context.createGain();
source.frequency.value = 1;
source.connect(gain);
gain.gain.value = 0;
gain.connect(g_context.destination);
if (source.start) {
source.start(0);
} else {
source.noteOn(0);
}
setTimeout(function() {
source.disconnect();
}, 100);
}
if (count == 3) {
for (var ii = 0; ii < eventNames.length; ++ii) {
elem.removeEventListener(eventNames[ii], playSoundToStartAudio, false);
}
g_eventEmitter.emit('started');
}
}
for (var ii = 0; ii < eventNames.length; ++ii) {
elem.addEventListener(eventNames[ii], playSoundToStartAudio, false);
}
}
}.bind(this);
this.loadSound = function(soundName, filename, samples, opt_callback) {
var ext = filename.substring(filename.length - 3);
if (ext == 'ogg' && !g_canPlayOgg) {
filename = changeExt(filename, "mp3");
} else if (ext == 'mp3' && !g_canPlayMp3) {
filename = changeExt(filename, "ogg");
}
var s = new g_createFromFileFn(soundName, filename, samples, opt_callback);
g_soundBank[soundName] = s;
return s;
}.bind(this);
this.makeJSFXSound = function(soundName, data, samples, opt_callback) {
var s = new g_createFromJSFXFn(soundName, data, samples, opt_callback);
g_soundBank[soundName] = s;
return s;
}.bind(this);
this.loadSounds = function(sounds, opt_callback) {
var soundsPending = 1;
var soundsLoaded = function() {
--soundsPending;
if (soundsPending == 0 && opt_callback) {
opt_callback();
}
};
Object.keys(sounds).forEach(function(sound) {
var data = sounds[sound];
++soundsPending;
if (data.jsfx) {
this.makeJSFXSound(sound, data.jsfx, data.samples, soundsLoaded);
} else {
this.loadSound(sound, data.filename, data.samples, soundsLoaded);
}
}.bind(this));
// so that we generate a callback even if there are no sounds.
// That way users don't have to restructure their code if they have no sounds or if they
// disable sounds by passing none in.
setTimeout(soundsLoaded, 0);
};
this.init = function(sounds) {
var a = new Audio()
g_canPlayOgg = a.canPlayType("audio/ogg");
g_canPlayMp3 = a.canPlayType("audio/mp3");
g_canPlayWav = a.canPlayType("audio/wav");
g_canPlayAif = a.canPlayType("audio/aif") || a.canPlayType("audio/aiff");
g_canPlay = g_canPlayOgg || g_canPlayMp3;
if (!g_canPlay)
return;
if (webAudioAPI) {
console.log("Using Web Audio API");
g_context = new webAudioAPI();
if (!g_context.createGain) { g_context.createGain = g_context.createGainNode.bind(g_context); }
g_createFromFileFn = WebAudioSound;
g_createFromJSFXFn = WebAudioJSFX;
} else {
console.log("Using Audio Tag");
g_createFromFileFn = AudioTagSound;
g_createFromJSFXFn = AudioTagJSFX;
}
var soundsPending = 1;
var soundsLoaded = function() {
--soundsPending;
if (soundsPending == 0) {
g_eventEmitter.emit('loaded');
}
};
if (sounds) {
Object.keys(sounds).forEach(function(sound) {
var data = sounds[sound];
++soundsPending;
if (data.jsfx) {
this.makeJSFXSound(sound, data.jsfx, data.samples, soundsLoaded);
} else {
this.loadSound(sound, data.filename, data.samples, soundsLoaded);
}
}.bind(this));
}
// so that we generate a callback even if there are no sounds.
// That way users don't have to restructure their code if they have no sounds or if they
// disable sounds by passing none in.
setTimeout(soundsLoaded, 0);
if (webAudioAPI) {
setupGesture();
}
}.bind(this);
this.init(sounds);
this.getSoundIds = function() {
return Object.keys(g_soundBank);
};
};
AudioManager.hasWebAudio = function() {
return webAudioAPI !== undefined;
};
return AudioManager;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0), __webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(audio, jsfx) {
var jsfxlib = {};
(function () {
// takes object with param arrays
// audiolib = {
// Sound : ["sine", 1, 2, 4, 1...
// }
//
// returns object with audio samples
// p.Sound.play()
this.createWaves = function(lib){
var sounds = {};
for (var e in lib) {
var data = lib[e];
sounds[e] = this.createWave(data);
}
return sounds;
}
/* Create a single sound:
var p = jsfxlib.createWave(["sine", 1,2,3, etc.]);
p.play();
*/
this.createWave = function(lib) {
var params = this.arrayToParams(lib),
data = jsfx.generate(params),
wave = audio.make(data);
return wave;
}
// takes object with param arrays
//
// var audiolib = {
// someSound : ["sine", 1, 2, 4, 1...
// }
//
// returns object with AudioBuffers you can use
// with the Web Audio API
//
// var sounds = jsfxlib.createAudioBuffers(ctx, audiolib);
// var ctx = new AudioContext();
// var src = ctx.createBufferSource();
// src.buffer = sounds.someSound;
// src.connect(ctx.destination);
// src.start();
this.createAudioBuffers = function(ctx, lib) {
var sounds = {};
for (var e in lib) {
var data = lib[e];
sounds[e] = this.createAudioBuffer(ctx, data);
}
return sounds;
}
// Create a single AudioBuffer
//
// var buffer = jsfxlib.createAudioBuffer(ctx, ["sine", 1,2,3, etc.]);
// var ctx = new AudioContext();
// var src = ctx.createBufferSource();
// src.buffer = buffer;
// src.connect(ctx.destination);
// src.start();
this.createAudioBuffer = function(ctx, lib) {
var params = this.arrayToParams(lib),
data = jsfx.generate(params),
buffer = audio.makeAudioBuffer(ctx, data);
return buffer;
}
this.paramsToArray = function(params){
var pararr = [];
var len = jsfx.Parameters.length;
for(var i = 0; i < len; i++){
pararr.push(params[jsfx.Parameters[i].id]);
}
return pararr;
}
this.arrayToParams = function(pararr){
var params = {};
var len = jsfx.Parameters.length;
for(var i = 0; i < len; i++){
params[jsfx.Parameters[i].id] = pararr[i];
}
return params;
}
}).apply(jsfxlib);
return jsfxlib;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(audio) {
var jsfx = {};
(function () {
this.Parameters = []; // will be constructed in the end
this.Generators = {
square : audio.generators.square,
saw : audio.generators.saw,
sine : audio.generators.sine,
noise : audio.generators.noise,
synth : audio.generators.synth
};
this.getGeneratorNames = function(){
var names = [];
for(var e in this.Generators)
names.push(e);
return names;
}
var nameToParam = function(name){
return name.replace(/ /g, "");
}
this.getParameters = function () {
var params = [];
var grp = 0;
// add param
var ap = function (name, min, max, def, step) {
if (step === undefined)
step = (max - min) / 1000;
var param = { name: name, id: nameToParam(name),
min: min, max: max, step:step, def: def,
type: "range", group: grp};
params.push(param);
};
// add option
var ao = function(name, options, def){
var param = {name: name, id: nameToParam(name),
options: options, def: def,
type: "option", group: grp };
params.push(param);
}
var gens = this.getGeneratorNames();
ao("Generator", gens, gens[0]);
ap("Super Sampling Quality", 0, 16, 0, 1);
ap("Master Volume", 0, 1, 0.4);
grp++;
ap("Attack Time", 0, 1, 0.1); // seconds
ap("Sustain Time", 0, 2, 0.3); // seconds
ap("Sustain Punch", 0, 3, 2);
ap("Decay Time", 0, 2, 1); // seconds
grp++;
ap("Min Frequency", 20, 2400, 0, 1);
ap("Start Frequency", 20, 2400, 440, 1);
ap("Max Frequency", 20, 2400, 2000, 1);
ap("Slide", -1, 1, 0);
ap("Delta Slide", -1, 1, 0);
grp++;
ap("Vibrato Depth", 0, 1, 0);
ap("Vibrato Frequency", 0.01, 48, 8);
ap("Vibrato Depth Slide", -0.3, 1, 0);
ap("Vibrato Frequency Slide", -1, 1, 0);
grp++;
ap("Change Amount", -1, 1, 0);
ap("Change Speed", 0, 1, 0.1);
grp++;
ap("Square Duty", 0, 0.5, 0);
ap("Square Duty Sweep", -1, 1, 0);
grp++;
ap("Repeat Speed", 0, 0.8, 0);
grp++;
ap("Phaser Offset", -1, 1, 0);
ap("Phaser Sweep", -1, 1, 0);
grp++;
ap("LP Filter Cutoff", 0, 1, 1);
ap("LP Filter Cutoff Sweep", -1, 1, 0);
ap("LP Filter Resonance", 0, 1, 0);
ap("HP Filter Cutoff", 0, 1, 0);
ap("HP Filter Cutoff Sweep", -1, 1, 0);
return params;
};
/**
* Input params object has the same parameters as described above
* except all the spaces have been removed
*
* This returns an array of float values of the generated audio.
*
* To make it into a wave use:
* data = jsfx.generate(params)
* audio.make(data)
*/
this.generate = function(params){
// useful consts/functions
var TAU = 2 * Math.PI,
sin = Math.sin,
cos = Math.cos,
pow = Math.pow,
abs = Math.abs;