-
Notifications
You must be signed in to change notification settings - Fork 0
/
howler.js
executable file
·1181 lines (997 loc) · 32 KB
/
howler.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
/*!
* howler.js v1.1.11
* howlerjs.com
*
* (c) 2013, James Simpson of GoldFire Studios
* goldfirestudios.com
*
* MIT License
*/
(function() {
// setup
var cache = {};
// setup the audio context
var ctx = null,
usingWebAudio = true,
noAudio = false;
if (typeof AudioContext !== 'undefined') {
ctx = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
ctx = new webkitAudioContext();
} else if (typeof Audio !== 'undefined') {
usingWebAudio = false;
} else {
usingWebAudio = false;
noAudio = true;
}
// create a master gain node
if (usingWebAudio) {
var masterGain = (typeof ctx.createGain === 'undefined') ? ctx.createGainNode() : ctx.createGain();
masterGain.gain.value = 1;
masterGain.connect(ctx.destination);
}
// create global controller
var HowlerGlobal = function() {
this._volume = 1;
this._muted = false;
this.usingWebAudio = usingWebAudio;
this._howls = [];
};
HowlerGlobal.prototype = {
/**
* Get/set the global volume for all sounds.
* @param {Float} vol Volume from 0.0 to 1.0.
* @return {Howler/Float} Returns self or current volume.
*/
volume: function(vol) {
var self = this;
// make sure volume is a number
vol = parseFloat(vol);
if (vol && vol >= 0 && vol <= 1) {
self._volume = vol;
if (usingWebAudio) {
masterGain.gain.value = vol;
}
// loop through cache and change volume of all nodes that are using HTML5 Audio
for (var key in self._howls) {
if (self._howls.hasOwnProperty(key) && self._howls[key]._webAudio === false) {
// loop through the audio nodes
for (var i=0; i<self._howls[key]._audioNode.length; i++) {
self._howls[key]._audioNode[i].volume = self._howls[key]._volume * self._volume;
}
}
}
return self;
}
// return the current global volume
return (usingWebAudio) ? masterGain.gain.value : self._volume;
},
/**
* Mute all sounds.
* @return {Howler}
*/
mute: function() {
this._setMuted(true);
return this;
},
/**
* Unmute all sounds.
* @return {Howler}
*/
unmute: function() {
this._setMuted(false);
return this;
},
/**
* Handle muting and unmuting globally.
* @param {Boolean} muted Is muted or not.
*/
_setMuted: function(muted) {
var self = this;
self._muted = muted;
if (usingWebAudio) {
masterGain.gain.value = muted ? 0 : self._volume;
}
for (var key in self._howls) {
if (self._howls.hasOwnProperty(key) && self._howls[key]._webAudio === false) {
// loop through the audio nodes
for (var i=0; i<self._howls[key]._audioNode.length; i++) {
self._howls[key]._audioNode[i].muted = muted;
}
}
}
}
};
// allow access to the global audio controls
var Howler = new HowlerGlobal();
// check for browser codec support
var audioTest = null;
if (!noAudio) {
audioTest = new Audio();
var codecs = {
mp3: !!audioTest.canPlayType('audio/mpeg;').replace(/^no$/,''),
opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,''),
ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''),
wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/,''),
m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/,''),
webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,'')
};
}
// setup the audio object
var Howl = function(o) {
var self = this;
// setup the defaults
self._autoplay = o.autoplay || false;
self._buffer = o.buffer || false;
self._duration = o.duration || 0;
self._format = o.format || null;
self._loop = o.loop || false;
self._loaded = false;
self._sprite = o.sprite || {};
self._src = o.src || '';
self._pos3d = o.pos3d || [0, 0, -0.5];
self._volume = o.volume || 1;
self._urls = o.urls || [];
// setup event functions
self._onload = [o.onload || function() {}];
self._onloaderror = [o.onloaderror || function() {}];
self._onend = [o.onend || function() {}];
self._onpause = [o.onpause || function() {}];
self._onplay = [o.onplay || function() {}];
self._onendTimer = [];
// Web Audio or HTML5 Audio?
self._webAudio = usingWebAudio && !self._buffer;
// check if we need to fall back to HTML5 Audio
self._audioNode = [];
if (self._webAudio) {
self._setupAudioNode();
}
// add this to an array of Howl's to allow global control
Howler._howls.push(self);
// load the track
self.load();
};
// setup all of the methods
Howl.prototype = {
/**
* Load an audio file.
* @return {Howl}
*/
load: function() {
var self = this,
url = null;
// if no audio is available, quit immediately
if (noAudio) {
self.on('loaderror');
return;
}
var canPlay = {
mp3: codecs.mp3,
opus: codecs.opus,
ogg: codecs.ogg,
wav: codecs.wav,
m4a: codecs.m4a,
weba: codecs.webm
};
// loop through source URLs and pick the first one that is compatible
for (var i=0; i<self._urls.length; i++) {
var ext;
if (self._format) {
// use specified audio format if available
ext = self._format;
} else {
// figure out the filetype (whether an extension or base64 data)
ext = self._urls[i].toLowerCase().match(/.+\.([^?]+)(\?|$)/);
ext = (ext && ext.length >= 2) ? ext[1] : self._urls[i].toLowerCase().match(/data\:audio\/([^?]+);/)[1];
}
if (canPlay[ext]) {
url = self._urls[i];
break;
}
}
if (!url) {
self.on('loaderror');
return;
}
self._src = url;
if (self._webAudio) {
loadBuffer(self, url);
} else {
var newNode = new Audio();
self._audioNode.push(newNode);
// setup the new audio node
newNode.src = url;
newNode._pos = 0;
newNode.preload = 'auto';
newNode.volume = (Howler._muted) ? 0 : self._volume * Howler.volume();
// add this sound to the cache
cache[url] = self;
// setup the event listener to start playing the sound
// as soon as it has buffered enough
var listener = function() {
self._duration = newNode.duration;
// setup a sprite if none is defined
if (Object.getOwnPropertyNames(self._sprite).length === 0) {
self._sprite = {_default: [0, self._duration * 1000]};
}
if (!self._loaded) {
self._loaded = true;
self.on('load');
}
if (self._autoplay) {
self.play();
}
// clear the event listener
newNode.removeEventListener('canplaythrough', listener, false);
};
newNode.addEventListener('canplaythrough', listener, false);
newNode.load();
}
return self;
},
/**
* Get/set the URLs to be pulled from to play in this source.
* @param {Array} urls Arry of URLs to load from
* @return {Howl} Returns self or the current URLs
*/
urls: function(urls) {
var self = this;
if (urls) {
self.stop();
self._urls = (typeof urls === 'string') ? [urls] : urls;
self._loaded = false;
self.load();
return self;
} else {
return self._urls;
}
},
/**
* Play a sound from the current time (0 by default).
* @param {String} sprite (optional) Plays from the specified position in the sound sprite definition.
* @param {Function} callback (optional) Returns the unique playback id for this sound instance.
* @return {Howl}
*/
play: function(sprite, callback) {
var self = this;
// if no sprite was passed but a callback was, update the variables
if (typeof sprite === 'function') {
callback = sprite;
}
// use the default sprite if none is passed
if (!sprite || typeof sprite === 'function') {
sprite = '_default';
}
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('load', function() {
self.play(sprite, callback);
});
return self;
}
// if the sprite doesn't exist, play nothing
if (!self._sprite[sprite]) {
if (typeof callback === 'function') callback();
return self;
}
// get the node to playback
self._inactiveNode(function(node) {
// persist the sprite being played
node._sprite = sprite;
// determine where to start playing from
var pos = (node._pos > 0) ? node._pos : self._sprite[sprite][0] / 1000,
duration = self._sprite[sprite][1] / 1000 - node._pos;
// determine if this sound should be looped
var loop = !!(self._loop || self._sprite[sprite][2]);
// set timer to fire the 'onend' event
var soundId = (typeof callback === 'string') ? callback : Math.round(Date.now() * Math.random()) + '',
timerId;
(function() {
var data = {
id: soundId,
sprite: sprite,
loop: loop
};
timerId = setTimeout(function() {
// if looping, restart the track
if (!self._webAudio && loop) {
self.stop(data.id, data.timer).play(sprite, data.id);
}
// set web audio node to paused at end
if (self._webAudio && !loop) {
self._nodeById(data.id).paused = true;
}
// end the track if it is HTML audio and a sprite
if (!self._webAudio && !loop) {
self.stop(data.id, data.timer);
}
// fire ended event
self.on('end', soundId);
}, duration * 1000);
// store the reference to the timer
self._onendTimer.push(timerId);
// remember which timer to cancel
data.timer = self._onendTimer[self._onendTimer.length - 1];
})();
if (self._webAudio) {
var loopStart = self._sprite[sprite][0] / 1000,
loopEnd = self._sprite[sprite][1] / 1000;
// set the play id to this node and load into context
node.id = soundId;
node.paused = false;
refreshBuffer(self, [loop, loopStart, loopEnd], soundId);
self._playStart = ctx.currentTime;
node.gain.value = self._volume;
if (typeof node.bufferSource.start === 'undefined') {
node.bufferSource.noteGrainOn(0, pos, duration);
} else {
node.bufferSource.start(0, pos, duration);
}
} else {
if (node.readyState === 4) {
node.id = soundId;
node.currentTime = pos;
node.muted = Howler._muted;
node.volume = self._volume * Howler.volume();
setTimeout(function() { node.play(); }, 0);
} else {
self._clearEndTimer(timerId);
(function(){
var sound = self,
playSprite = sprite,
fn = callback,
newNode = node;
var listener = function() {
sound.play(playSprite, fn);
// clear the event listener
newNode.removeEventListener('canplaythrough', listener, false);
};
newNode.addEventListener('canplaythrough', listener, false);
})();
return self;
}
}
// fire the play event and send the soundId back in the callback
self.on('play');
if (typeof callback === 'function') callback(soundId);
return self;
});
return self;
},
/**
* Pause playback and save the current position.
* @param {String} id (optional) The play instance ID.
* @param {String} timerId (optional) Clear the correct timeout ID.
* @return {Howl}
*/
pause: function(id, timerId) {
var self = this;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('play', function() {
self.pause(id);
});
return self;
}
// clear 'onend' timer
self._clearEndTimer(timerId || 0);
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
activeNode._pos = self.pos(null, id);
if (self._webAudio) {
// make sure the sound has been created
if (!activeNode.bufferSource) {
return self;
}
activeNode.paused = true;
if (typeof activeNode.bufferSource.stop === 'undefined') {
activeNode.bufferSource.noteOff(0);
} else {
activeNode.bufferSource.stop(0);
}
} else {
activeNode.pause();
}
}
self.on('pause');
return self;
},
/**
* Stop playback and reset to start.
* @param {String} id (optional) The play instance ID.
* @param {String} timerId (optional) Clear the correct timeout ID.
* @return {Howl}
*/
stop: function(id, timerId) {
var self = this;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('play', function() {
self.stop(id);
});
return self;
}
// clear 'onend' timer
self._clearEndTimer(timerId || 0);
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
activeNode._pos = 0;
if (self._webAudio) {
// make sure the sound has been created
if (!activeNode.bufferSource) {
return self;
}
activeNode.paused = true;
if (typeof activeNode.bufferSource.stop === 'undefined') {
activeNode.bufferSource.noteOff(0);
} else {
activeNode.bufferSource.stop(0);
}
} else {
activeNode.pause();
activeNode.currentTime = 0;
}
}
return self;
},
/**
* Mute this sound.
* @param {String} id (optional) The play instance ID.
* @return {Howl}
*/
mute: function(id) {
var self = this;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('play', function() {
self.mute(id);
});
return self;
}
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
if (self._webAudio) {
activeNode.gain.value = 0;
} else {
activeNode.volume = 0;
}
}
return self;
},
/**
* Unmute this sound.
* @param {String} id (optional) The play instance ID.
* @return {Howl}
*/
unmute: function(id) {
var self = this;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('play', function() {
self.unmute(id);
});
return self;
}
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
if (self._webAudio) {
activeNode.gain.value = self._volume;
} else {
activeNode.volume = self._volume;
}
}
return self;
},
/**
* Get/set volume of this sound.
* @param {Float} vol Volume from 0.0 to 1.0.
* @param {String} id (optional) The play instance ID.
* @return {Howl/Float} Returns self or current volume.
*/
volume: function(vol, id) {
var self = this;
// make sure volume is a number
vol = parseFloat(vol);
if (vol >= 0 && vol <= 1) {
self._volume = vol;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('play', function() {
self.volume(vol, id);
});
return self;
}
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
if (self._webAudio) {
activeNode.gain.value = vol;
} else {
activeNode.volume = vol * Howler.volume();
}
}
return self;
} else {
return self._volume;
}
},
/**
* Get/set whether to loop the sound.
* @param {Boolean} loop To loop or not to loop, that is the question.
* @return {Howl/Boolean} Returns self or current looping value.
*/
loop: function(loop) {
var self = this;
if (typeof loop === 'boolean') {
self._loop = loop;
return self;
} else {
return self._loop;
}
},
/**
* Get/set sound sprite definition.
* @param {Object} sprite Example: {spriteName: [offset, duration, loop]}
* @param {Integer} offset Where to begin playback in milliseconds
* @param {Integer} duration How long to play in milliseconds
* @param {Boolean} loop (optional) Set true to loop this sprite
* @return {Howl} Returns current sprite sheet or self.
*/
sprite: function(sprite) {
var self = this;
if (typeof sprite === 'object') {
self._sprite = sprite;
return self;
} else {
return self._sprite;
}
},
/**
* Get/set the position of playback.
* @param {Float} pos The position to move current playback to.
* @param {String} id (optional) The play instance ID.
* @return {Howl/Float} Returns self or current playback position.
*/
pos: function(pos, id) {
var self = this;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('load', function() {
self.pos(pos);
});
return typeof pos === 'number' ? self : self._pos || 0;
}
// make sure we are dealing with a number for pos
pos = parseFloat(pos);
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
if (self._webAudio) {
if (pos >= 0) {
activeNode._pos = pos;
self.pause(id).play(activeNode._sprite, id);
return self;
} else {
return activeNode._pos + (ctx.currentTime - self._playStart);
}
} else {
if (pos >= 0) {
activeNode.currentTime = pos;
return self;
} else {
return activeNode.currentTime;
}
}
} else if (pos >= 0) {
return self;
} else {
// find the first inactive node to return the pos for
for (var i=0; i<self._audioNode.length; i++) {
if (self._audioNode[i].paused && self._audioNode[i].readyState === 4) {
return (self._webAudio) ? self._audioNode[i]._pos : self._audioNode[i].currentTime;
}
}
}
},
/**
* Get/set the 3D position of the audio source.
* The most common usage is to set the 'x' position
* to affect the left/right ear panning. Setting any value higher than
* 1.0 will begin to decrease the volume of the sound as it moves further away.
* NOTE: This only works with Web Audio API, HTML5 Audio playback
* will not be affected.
* @param {Float} x The x-position of the playback from -1000.0 to 1000.0
* @param {Float} y The y-position of the playback from -1000.0 to 1000.0
* @param {Float} z The z-position of the playback from -1000.0 to 1000.0
* @param {String} id (optional) The play instance ID.
* @return {Howl/Array} Returns self or the current 3D position: [x, y, z]
*/
pos3d: function(x, y, z, id) {
var self = this;
// set a default for the optional 'y' & 'z'
y = (typeof y === 'undefined' || !y) ? 0 : y;
z = (typeof z === 'undefined' || !z) ? -0.5 : z;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('play', function() {
self.pos3d(x, y, z, id);
});
return self;
}
if (x >= 0 || x < 0) {
if (self._webAudio) {
var activeNode = (id) ? self._nodeById(id) : self._activeNode();
if (activeNode) {
self._pos3d = [x, y, z];
activeNode.panner.setPosition(x, y, z);
}
}
} else {
return self._pos3d;
}
return self;
},
/**
* Fade a currently playing sound between two volumes.
* @param {Number} from The volume to fade from (0.0 to 1.0).
* @param {Number} to The volume to fade to (0.0 to 1.0).
* @param {Number} len Time in milliseconds to fade.
* @param {Function} callback (optional) Fired when the fade is complete.
* @param {String} id (optional) The play instance ID.
* @return {Howl}
*/
fade: function(from, to, len, callback, id) {
var self = this,
diff = Math.abs(from - to),
dir = from > to ? 'down' : 'up',
steps = diff / 0.01,
stepTime = len / steps;
// if the sound hasn't been loaded, add it to the event queue
if (!self._loaded) {
self.on('load', function() {
self.fade(from, to, len, callback, id);
});
return self;
}
// set the volume to the start position
self.volume(from, id);
for (var i=1; i<=steps; i++) {
(function() {
var change = self._volume + (dir === 'up' ? 0.01 : -0.01) * i,
vol = Math.round(1000 * change) / 1000,
toVol = to;
setTimeout(function() {
self.volume(vol, id);
if (vol === toVol) {
if (callback) callback();
}
}, stepTime * i);
})();
}
},
/**
* [DEPRECATED] Fade in the current sound.
* @param {Float} to Volume to fade to (0.0 to 1.0).
* @param {Number} len Time in milliseconds to fade.
* @param {Function} callback
* @return {Howl}
*/
fadeIn: function(to, len, callback) {
return this.volume(0).play().fade(0, to, len, callback);
},
/**
* [DEPRECATED] Fade out the current sound and pause when finished.
* @param {Float} to Volume to fade to (0.0 to 1.0).
* @param {Number} len Time in milliseconds to fade.
* @param {Function} callback
* @param {String} id (optional) The play instance ID.
* @return {Howl}
*/
fadeOut: function(to, len, callback, id) {
var self = this;
return self.fade(self._volume, to, len, function() {
if (callback) callback();
self.pause(id);
// fire ended event
self.on('end');
}, id);
},
/**
* Get an audio node by ID.
* @return {Howl} Audio node.
*/
_nodeById: function(id) {
var self = this,
node = self._audioNode[0];
// find the node with this ID
for (var i=0; i<self._audioNode.length; i++) {
if (self._audioNode[i].id === id) {
node = self._audioNode[i];
break;
}
}
return node;
},
/**
* Get the first active audio node.
* @return {Howl} Audio node.
*/
_activeNode: function() {
var self = this,
node = null;
// find the first playing node
for (var i=0; i<self._audioNode.length; i++) {
if (!self._audioNode[i].paused) {
node = self._audioNode[i];
break;
}
}
// remove excess inactive nodes
self._drainPool();
return node;
},
/**
* Get the first inactive audio node.
* If there is none, create a new one and add it to the pool.
* @param {Function} callback Function to call when the audio node is ready.
*/
_inactiveNode: function(callback) {
var self = this,
node = null;
// find first inactive node to recycle
for (var i=0; i<self._audioNode.length; i++) {
if (self._audioNode[i].paused && self._audioNode[i].readyState === 4) {
callback(self._audioNode[i]);
node = true;
break;
}
}
// remove excess inactive nodes
self._drainPool();
if (node) {
return;
}
// create new node if there are no inactives
var newNode;
if (self._webAudio) {
newNode = self._setupAudioNode();
callback(newNode);
} else {
self.load();
newNode = self._audioNode[self._audioNode.length - 1];
newNode.addEventListener('loadedmetadata', function() {
callback(newNode);
});
}
},
/**
* If there are more than 5 inactive audio nodes in the pool, clear out the rest.
*/
_drainPool: function() {
var self = this,
inactive = 0,
i;
// count the number of inactive nodes
for (i=0; i<self._audioNode.length; i++) {
if (self._audioNode[i].paused) {
inactive++;
}
}
// remove excess inactive nodes
for (i=self._audioNode.length-1; i>=0; i--) {
if (inactive <= 5) {
break;
}
if (self._audioNode[i].paused) {
// disconnect the audio source if using Web Audio
if (self._webAudio) {
self._audioNode[i].disconnect(0);
}
inactive--;
self._audioNode.splice(i, 1);
}
}
},
/**
* Clear 'onend' timeout before it ends.
* @param {Number} timerId The ID of the sound to be cancelled.
*/
_clearEndTimer: function(timerId) {
var self = this,
timer = self._onendTimer.indexOf(timerId);
// make sure the timer gets cleared
timer = timer >= 0 ? timer : 0;
if (self._onendTimer[timer]) {
clearTimeout(self._onendTimer[timer]);
self._onendTimer.splice(timer, 1);
}
},
/**
* Setup the gain node and panner for a Web Audio instance.
* @return {Object} The new audio node.
*/
_setupAudioNode: function() {
var self = this,
node = self._audioNode,
index = self._audioNode.length;
// create gain node
node[index] = (typeof ctx.createGain === 'undefined') ? ctx.createGainNode() : ctx.createGain();
node[index].gain.value = self._volume;
node[index].paused = true;
node[index]._pos = 0;
node[index].readyState = 4;
node[index].connect(masterGain);
// create the panner
node[index].panner = ctx.createPanner();
node[index].panner.setPosition(self._pos3d[0], self._pos3d[1], self._pos3d[2]);
node[index].panner.connect(node[index]);
return node[index];
},
/**
* Call/set custom events.
* @param {String} event Event type.
* @param {Function} fn Function to call.
* @return {Howl}
*/
on: function(event, fn) {
var self = this,
events = self['_on' + event];
if (typeof fn === "function") {