-
Notifications
You must be signed in to change notification settings - Fork 0
/
howler.js
1353 lines (1145 loc) · 37.6 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.25
* howlerjs.com
*
* (c) 2013-2014, James Simpson of GoldFire Studios
* goldfirestudios.com
*
* MIT License
*/
(function() {
// setup
var cache = {};
// setup the audio context
var ctx = null,
usingWebAudio = true,
noAudio = false;
try {
if (typeof AudioContext !== 'undefined') {
ctx = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
ctx = new webkitAudioContext();
} else {
usingWebAudio = false;
}
} catch(e) {
usingWebAudio = false;
}
if (!usingWebAudio) {
if (typeof Audio !== 'undefined') {
try {
new Audio();
} catch(e) {
noAudio = true;
}
} else {
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(codecs) {
this._volume = 1;
this._muted = false;
this.usingWebAudio = usingWebAudio;
this.ctx = ctx;
this.noAudio = noAudio;
this._howls = [];
this._codecs = codecs;
this.iOSAutoEnable = true;
};
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 >= 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;
}
}
}
},
/**
* Check for codec support.
* @param {String} ext Audio file extention.
* @return {Boolean}
*/
codecs: function(ext) {
return this._codecs[ext];
},
/**
* iOS will only allow audio to be played after a user interaction.
* Attempt to automatically unlock audio on the first user interaction.
* Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
* @return {Howler}
*/
_enableiOSAudio: function() {
var self = this;
// only run this on iOS if audio isn't already eanbled
if (ctx && (self._iOSEnabled || !/iPhone|iPad|iPod/i.test(navigator.userAgent))) {
return;
}
self._iOSEnabled = false;
// call this method on touch start to create and play a buffer,
// then check if the audio actually played to determine if
// audio has now been unlocked on iOS
var unlock = function() {
// create an empty buffer
var buffer = ctx.createBuffer(1, 1, 22050);
var source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(ctx.destination);
// play the empty buffer
if (typeof source.start === 'undefined') {
source.noteOn(0);
} else {
source.start(0);
}
// setup a timeout to check that we are unlocked on the next event loop
setTimeout(function() {
if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
// update the unlocked state and prevent this check from happening again
self._iOSEnabled = true;
self.iOSAutoEnable = false;
// remove the touch start listener
window.removeEventListener('touchstart', unlock, false);
}
}, 0);
};
// setup a touch start listener to attempt an unlock in
window.addEventListener('touchstart', unlock, false);
return self;
}
};
// check for browser codec support
var audioTest = null;
var codecs = {};
if (!noAudio) {
audioTest = new Audio();
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$/, ''),
aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')
};
}
// allow access to the global audio controls
var Howler = new HowlerGlobal(codecs);
// 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 !== undefined ? o.volume : 1;
self._urls = o.urls || [];
self._rate = o.rate || 1;
// allow forcing of a specific panningModel ('equalpower' or 'HRTF'),
// if none is specified, defaults to 'equalpower' and switches to 'HRTF'
// if 3d sound is used
self._model = o.model || null;
// 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();
}
// automatically try to enable audio on iOS
if (typeof ctx !== 'undefined' && ctx && Howler.iOSAutoEnable) {
Howler._enableiOSAudio();
}
// 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;
}
// loop through source URLs and pick the first one that is compatible
for (var i=0; i<self._urls.length; i++) {
var ext, urlItem;
if (self._format) {
// use specified audio format if available
ext = self._format;
} else {
// figure out the filetype (whether an extension or base64 data)
urlItem = self._urls[i];
ext = /^data:audio\/([^;,]+);/i.exec(urlItem);
if (!ext) {
ext = /\.([^.]+)$/.exec(urlItem.split('?', 1)[0]);
}
if (ext) {
ext = ext[1].toLowerCase();
} else {
self.on('loaderror');
return;
}
}
if (codecs[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();
// listen for errors with HTML5 audio (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror)
newNode.addEventListener('error', function () {
if (newNode.error && newNode.error.code === 4) {
HowlerGlobal.noAudio = true;
}
self.on('loaderror', {type: newNode.error ? newNode.error.code : 0});
}, false);
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();
// setup the event listener to start playing the sound
// as soon as it has buffered enough
var listener = function() {
// round up the duration when using HTML5 Audio to account for the lower precision
self._duration = Math.ceil(newNode.duration * 10) / 10;
// 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;
// determine how long to play for
var duration = 0;
if (self._webAudio) {
duration = self._sprite[sprite][1] / 1000 - node._pos;
if (node._pos > 0) {
pos = self._sprite[sprite][0] / 1000 + pos;
}
} else {
duration = self._sprite[sprite][1] / 1000 - (pos - self._sprite[sprite][0] / 1000);
}
// 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).play(sprite, data.id);
}
// set web audio node to paused at end
if (self._webAudio && !loop) {
self._nodeById(data.id).paused = true;
self._nodeById(data.id)._pos = 0;
// clear the end timer
self._clearEndTimer(data.id);
}
// end the track if it is HTML audio and a sprite
if (!self._webAudio && !loop) {
self.stop(data.id);
}
// fire ended event
self.on('end', soundId);
}, duration * 1000);
// store the reference to the timer
self._onendTimer.push({timer: timerId, id: data.id});
})();
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.readyState && navigator.isCocoonJS) {
node.readyState = 4;
node.id = soundId;
node.currentTime = pos;
node.muted = Howler._muted || node.muted;
node.volume = self._volume * Howler.volume();
setTimeout(function() { node.play(); }, 0);
} else {
self._clearEndTimer(soundId);
(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.
* @return {Howl}
*/
pause: 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.pause(id);
});
return self;
}
// clear 'onend' timer
self._clearEndTimer(id);
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 || activeNode.paused) {
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.
* @return {Howl}
*/
stop: 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.stop(id);
});
return self;
}
// clear 'onend' timer
self._clearEndTimer(id);
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 || activeNode.paused) {
return self;
}
activeNode.paused = true;
if (typeof activeNode.bufferSource.stop === 'undefined') {
activeNode.bufferSource.noteOff(0);
} else {
activeNode.bufferSource.stop(0);
}
} else if (!isNaN(activeNode.duration)) {
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.muted = true;
}
}
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.muted = false;
}
}
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 (pos >= 0) {
self.pause(id);
activeNode._pos = pos;
self.play(activeNode._sprite, id);
return self;
} else {
return self._webAudio ? activeNode._pos + (ctx.currentTime - self._playStart) : 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);
activeNode.panner.panningModel = self._model || 'HRTF';
}
}
} 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) {
// send the node back for use by the new play instance
callback(self._audioNode[i]);
node = true;
break;
}
}
// remove excess inactive nodes
self._drainPool();