-
Notifications
You must be signed in to change notification settings - Fork 4
/
howler.core.js
1651 lines (1384 loc) · 57 KB
/
howler.core.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 v2.0.0-beta
* howlerjs.com
*
* (c) 2013-2015, James Simpson of GoldFire Studios
* goldfirestudios.com
*
* MIT License
*/
(function() {
'use strict';
// Setup our audio context.
var ctx = null;
var usingWebAudio = true;
var noAudio = false;
setupAudioContext();
// 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);
}
/** Global Methods **/
/***************************************************************************/
/**
* Create the global controller. All contained methods and properties apply
* to all sounds that are currently playing or will be in the future.
*/
var HowlerGlobal = function() {
this.init();
};
HowlerGlobal.prototype = {
/**
* Initialize the global Howler object.
* @return {Howler}
*/
init: function() {
var self = this || Howler;
// Internal properties.
self._codecs = {};
self._howls = [];
self._muted = false;
self._volume = 1;
// Set to false to disable the auto iOS enabler.
self.iOSAutoEnable = true;
// No audio is available on this system if this is set to true.
self.noAudio = noAudio;
// This will be true if the Web Audio API is available.
self.usingWebAudio = usingWebAudio;
// Expose the AudioContext when using Web Audio.
self.ctx = ctx;
// Check for supported codecs.
if (!noAudio) {
self._setupCodecs();
}
return self;
},
/**
* 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 || Howler;
vol = parseFloat(vol);
if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
self._volume = vol;
// When using Web Audio, we just need to adjust the master gain.
if (usingWebAudio) {
masterGain.gain.value = vol;
}
// Loop through and change volume for all HTML5 audio nodes.
for (var i=0; i<self._howls.length; i++) {
if (!self._howls[i]._webAudio) {
// Get all of the sounds in this Howl group.
var ids = self._howls[i]._getSoundIds();
// Loop through all sounds and change the volumes.
for (var j=0; j<ids.length; j++) {
var sound = self._howls[i]._soundById(ids[j]);
if (sound && sound._node) {
sound._node.volume = sound._volume * vol;
}
}
}
}
return self;
}
return self._volume;
},
/**
* Handle muting and unmuting globally.
* @param {Boolean} muted Is muted or not.
*/
mute: function(muted) {
var self = this || Howler;
self._muted = muted;
// With Web Audio, we just need to mute the master gain.
if (usingWebAudio) {
masterGain.gain.value = muted ? 0 : self._volume;
}
// Loop through and mute all HTML5 Audio nodes.
for (var i=0; i<self._howls.length; i++) {
if (!self._howls[i]._webAudio) {
// Get all of the sounds in this Howl group.
var ids = self._howls[i]._getSoundIds();
// Loop through all sounds and mark the audio node as muted.
for (var j=0; j<ids.length; j++) {
var sound = self._howls[i]._soundById(ids[j]);
if (sound && sound._node) {
sound._node.muted = (muted) ? true : sound._muted;
}
}
}
}
return self;
},
/**
* Check for codec support of specific extension.
* @param {String} ext Audio file extention.
* @return {Boolean}
*/
codecs: function(ext) {
return (this || Howler)._codecs[ext];
},
/**
* Check for browser support for various codecs and cache the results.
* @return {Howler}
*/
_setupCodecs: function() {
var self = this || Howler;
var audioTest = new Audio();
var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
self._codecs = {
mp3: !!(mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, '')),
mpeg: !!mpegTest,
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$/, ''),
webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')
};
return self;
},
/**
* iOS will only allow audio to be played after a user interaction.
* Attempt to automatically unlock audio on the first user interaction.
* Concept from: https://paulbakaus.com/tutorials/html5/web-audio-on-ios/
* @return {Howler}
*/
_enableiOSAudio: function() {
var self = this || Howler;
// 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;
}
};
// Setup the global audio controller.
var Howler = new HowlerGlobal();
/** Group Methods **/
/***************************************************************************/
/**
* Create an audio group controller.
* @param {Object} o Passed in properties for this group.
*/
var Howl = function(o) {
var self = this;
// Throw an error if no source is provided.
if (!o.src || o.src.length === 0) {
console.error('An array of source files must be passed with any new Howl.');
return;
}
self.init(o);
};
Howl.prototype = {
/**
* Initialize a new Howl group object.
* @param {Object} o Passed in properties for this group.
* @return {Howl}
*/
init: function(o) {
var self = this;
// Setup user-defined default properties.
self._autoplay = o.autoplay || false;
self._ext = o.ext || null;
self._html5 = o.html5 || false;
self._muted = o.mute || false;
self._loop = o.loop || false;
self._pool = o.pool || 5;
self._preload = (typeof o.preload === 'boolean') ? o.preload : true;
self._rate = o.rate || 1;
self._sprite = o.sprite || {};
self._src = (typeof o.src !== 'string') ? o.src : [o.src];
self._volume = o.volume !== undefined ? o.volume : 1;
// Setup all other default properties.
self._duration = 0;
self._loaded = false;
self._sounds = [];
self._endTimers = {};
// Setup event listeners.
self._onend = o.onend ? [{fn: o.onend}] : [];
self._onfaded = o.onfaded ? [{fn: o.onfaded}] : [];
self._onload = o.onload ? [{fn: o.onload}] : [];
self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
self._onpause = o.onpause ? [{fn: o.onpause}] : [];
self._onplay = o.onplay ? [{fn: o.onplay}] : [];
// Web Audio or HTML5 Audio?
self._webAudio = usingWebAudio && !self._html5;
// Automatically try to enable audio on iOS.
if (typeof ctx !== 'undefined' && ctx && Howler.iOSAutoEnable) {
Howler._enableiOSAudio();
}
// Keep track of this Howl group in the global controller.
Howler._howls.push(self);
// Load the source file unless otherwise specified.
if (self._preload) {
self.load();
}
return self;
},
/**
* Load the audio file.
* @return {Howler}
*/
load: function() {
var self = this;
var url = null;
// If no audio is available, quit immediately.
if (noAudio) {
self._emit('loaderror');
return;
}
// Make sure our source is in an array.
if (typeof self._src === 'string') {
self._src = [self._src];
}
// Loop through the sources and pick the first one that is compatible.
for (var i=0; i<self._src.length; i++) {
var ext, str;
if (self._ext && self._ext[i]) {
// If an extension was specified, use that instead.
ext = self._ext[i];
} else {
// Extract the file extension from the URL or base64 data URI.
str = self._src[i];
ext = /^data:audio\/([^;,]+);/i.exec(str);
if (!ext) {
ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]);
}
if (ext) {
ext = ext[1].toLowerCase();
}
}
// Check if this extension is available.
if (Howler.codecs(ext)) {
url = self._src[i];
break;
}
}
if (!url) {
self._emit('loaderror');
return;
}
self._src = url;
// Create a new sound object and add it to the pool.
new Sound(self);
// Load and decode the audio data for playback.
if (self._webAudio) {
loadBuffer(self);
}
return self;
},
/**
* Play a sound or resume previous playback.
* @param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
* @return {Number} Sound ID.
*/
play: function(sprite) {
var self = this;
var args = arguments;
var id = null;
// Determine if a sprite, sound id or nothing was passed
if (typeof sprite === 'number') {
id = sprite;
sprite = null;
} else if (typeof sprite === 'undefined') {
// Use the default sound sprite (plays the full audio length).
sprite = '__default';
// Check if there is a single paused sound that isn't ended.
// If there is, play that sound. If not, continue as usual.
var num = 0;
for (var i=0; i<self._sounds.length; i++) {
if (self._sounds[i]._paused && !self._sounds[i]._ended) {
num++;
id = self._sounds[i]._id;
}
}
if (num === 1) {
sprite = null;
} else {
id = null;
}
}
// Get the selected node, or get one from the pool.
var sound = id ? self._soundById(id) : self._inactiveSound();
// If the sound doesn't exist, do nothing.
if (!sound) {
return null;
}
// Select the sprite definition.
if (id && !sprite) {
sprite = sound._sprite || '__default';
}
// If we have no sprite and the sound hasn't loaded, we must wait
// for the sound to load to get our audio's duration.
if (!self._loaded && !self._sprite[sprite]) {
self.once('load', function() {
self.play(self._soundById(sound._id) ? sound._id : undefined);
});
return sound._id;
}
// Don't play the sound if an id was passed and it is already playing.
if (id && !sound._paused) {
return sound._id;
}
// Determine how long to play for and where to start playing.
var seek = sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000;
var duration = ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek;
// Create a timer to fire at the end of playback or the start of a new loop.
var ended = function() {
// Should this sound loop?
var loop = !!(sound._loop || self._sprite[sprite][2]);
// Fire the ended event.
self._emit('end', sound._id);
// Restart the playback for HTML5 Audio loop.
if (!self._webAudio && loop) {
self.stop(sound._id).play(sound._id);
}
// Restart this timer if on a Web Audio loop.
if (self._webAudio && loop) {
self._emit('play', sound._id);
sound._seek = sound._start || 0;
sound._playStart = ctx.currentTime;
self._endTimers[sound._id] = setTimeout(ended, ((sound._stop - sound._start) * 1000) / Math.abs(self._rate));
}
// Mark the node as paused.
if (self._webAudio && !loop) {
sound._paused = true;
sound._ended = true;
sound._seek = sound._start || 0;
self._clearTimer(sound._id);
// Clean up the buffer source.
sound._node.bufferSource = null;
}
// When using a sprite, end the track.
if (!self._webAudio && !loop) {
self.stop(sound._id);
}
};
self._endTimers[sound._id] = setTimeout(ended, (duration * 1000) / Math.abs(self._rate));
// Update the parameters of the sound
sound._paused = false;
sound._ended = false;
sound._sprite = sprite;
sound._seek = seek;
sound._start = self._sprite[sprite][0] / 1000;
sound._stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
sound._loop = !!(sound._loop || self._sprite[sprite][2]);
// Begin the actual playback.
var node = sound._node;
if (self._webAudio) {
// Fire this when the sound is ready to play to begin Web Audio playback.
var playWebAudio = function() {
self._refreshBuffer(sound);
// Setup the playback params.
var vol = (sound._muted || self._muted) ? 0 : sound._volume * Howler.volume();
node.gain.setValueAtTime(vol, ctx.currentTime);
sound._playStart = ctx.currentTime;
// Play the sound using the supported method.
if (typeof node.bufferSource.start === 'undefined') {
sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
} else {
sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
}
// Start a new timer if none is present.
if (!self._endTimers[sound._id]) {
self._endTimers[sound._id] = setTimeout(ended, (duration * 1000) / Math.abs(self._rate));
}
if (!args[1]) {
setTimeout(function() {
self._emit('play', sound._id);
}, 0);
}
};
if (self._loaded) {
playWebAudio();
} else {
// Wait for the audio to load and then begin playback.
self.once('load', playWebAudio);
// Cancel the end timer.
self._clearTimer(sound._id);
}
} else {
// Fire this when the sound is ready to play to begin HTML5 Audio playback.
var playHtml5 = function() {
node.currentTime = seek;
node.muted = sound._muted || self._muted || Howler._muted || node.muted;
node.volume = sound._volume * Howler.volume();
node.playbackRate = self._rate;
setTimeout(function() {
node.play();
if (!args[1]) {
self._emit('play', sound._id);
}
}, 0);
};
// Play immediately if ready, or wait for the 'canplaythrough'e vent.
if (node.readyState === 4 || !node.readyState && navigator.isCocoonJS) {
playHtml5();
} else {
var listener = function() {
// Setup the new end timer.
self._endTimers[sound._id] = setTimeout(ended, (duration * 1000) / Math.abs(self._rate));
// Begin playback.
playHtml5();
// Clear this listener.
node.removeEventListener('canplaythrough', listener, false);
};
node.addEventListener('canplaythrough', listener, false);
// Cancel the end timer.
self._clearTimer(sound._id);
}
}
return sound._id;
},
/**
* Pause playback and save current position.
* @param {Number} id The sound ID (empty to pause all in group).
* @return {Howl}
*/
pause: function(id) {
var self = this;
// Wait for the sound to begin playing before pausing it.
if (!self._loaded) {
self.once('play', function() {
self.pause(id);
});
return self;
}
// If no id is passed, get all ID's to be paused.
var ids = self._getSoundIds(id);
for (var i=0; i<ids.length; i++) {
// Clear the end timer.
self._clearTimer(ids[i]);
// Get the sound.
var sound = self._soundById(ids[i]);
if (sound && !sound._paused) {
// Reset the seek position.
sound._seek = self.seek(ids[i]);
sound._paused = true;
if (self._webAudio) {
// make sure the sound has been created
if (!sound._node.bufferSource) {
return self;
}
if (typeof sound._node.bufferSource.stop === 'undefined') {
sound._node.bufferSource.noteOff(0);
} else {
sound._node.bufferSource.stop(0);
}
// Clean up the buffer source.
sound._node.bufferSource = null;
} else if (!isNaN(sound._node.duration)) {
sound._node.pause();
}
// Fire the pause event, unless `true` is passed as the 2nd argument.
if (!arguments[1]) {
self._emit('pause', sound._id);
}
}
}
return self;
},
/**
* Stop playback and reset to start.
* @param {Number} id The sound ID (empty to stop all in group).
* @return {Howl}
*/
stop: function(id) {
var self = this;
// Wait for the sound to begin playing before stopping it.
if (!self._loaded) {
if (typeof self._sounds[0]._sprite !== 'undefined') {
self.once('play', function() {
self.stop(id);
});
}
return self;
}
// If no id is passed, get all ID's to be stopped.
var ids = self._getSoundIds(id);
for (var i=0; i<ids.length; i++) {
// Clear the end timer.
self._clearTimer(ids[i]);
// Get the sound.
var sound = self._soundById(ids[i]);
if (sound && !sound._paused) {
// Reset the seek position.
sound._seek = sound._start || 0;
sound._paused = true;
sound._ended = true;
if (self._webAudio && sound._node) {
// make sure the sound has been created
if (!sound._node.bufferSource) {
return self;
}
if (typeof sound._node.bufferSource.stop === 'undefined') {
sound._node.bufferSource.noteOff(0);
} else {
sound._node.bufferSource.stop(0);
}
// Clean up the buffer source.
sound._node.bufferSource = null;
} else if (sound._node && !isNaN(sound._node.duration)) {
sound._node.pause();
sound._node.currentTime = sound._start || 0;
}
}
}
return self;
},
/**
* Mute/unmute a single sound or all sounds in this Howl group.
* @param {Boolean} muted Set to true to mute and false to unmute.
* @param {Number} id The sound ID to update (omit to mute/unmute all).
* @return {Howl}
*/
mute: function(muted, id) {
var self = this;
// Wait for the sound to begin playing before muting it.
if (!self._loaded) {
self.once('play', function() {
self.mute(muted, id);
});
return self;
}
// If applying mute/unmute to all sounds, update the group's value.
if (typeof id === 'undefined') {
if (typeof muted === 'boolean') {
self._muted = muted;
} else {
return self._muted;
}
}
// If no id is passed, get all ID's to be muted.
var ids = self._getSoundIds(id);
for (var i=0; i<ids.length; i++) {
// Get the sound.
var sound = self._soundById(ids[i]);
if (sound) {
sound._muted = muted;
if (self._webAudio && sound._node) {
sound._node.gain.setValueAtTime(muted ? 0 : sound._volume * Howler.volume(), ctx.currentTime);
} else if (sound._node) {
sound._node.muted = Howler._muted ? true : muted;
}
}
}
return self;
},
/**
* Get/set the volume of this sound or of the Howl group. This method can optionally take 0, 1 or 2 arguments.
* volume() -> Returns the group's volume value.
* volume(id) -> Returns the sound id's current volume.
* volume(vol) -> Sets the volume of all sounds in this Howl group.
* volume(vol, id) -> Sets the volume of passed sound id.
* @return {Howl/Number} Returns self or current volume.
*/
volume: function() {
var self = this;
var args = arguments;
var vol, id;
// Determine the values based on arguments.
if (args.length === 0) {
// Return the value of the groups' volume.
return self._volume;
} else if (args.length === 1) {
// First check if this is an ID, and if not, assume it is a new volume.
var ids = self._getSoundIds();
var index = ids.indexOf(args[0]);
if (index >= 0) {
id = parseInt(args[0], 10);
} else {
vol = parseFloat(args[0]);
}
} else if (args.length === 2) {
vol = parseFloat(args[0]);
id = parseInt(args[1], 10);
}
// Update the volume or return the current volume.
var sound;
if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
// Wait for the sound to begin playing before changing the volume.
if (!self._loaded) {
self.once('play', function() {
self.volume.apply(self, args);
});
return self;
}
// Set the group volume.
if (typeof id === 'undefined') {
self._volume = vol;
}
// Update one or all volumes.
id = self._getSoundIds(id);
for (var i=0; i<id.length; i++) {
// Get the sound.
sound = self._soundById(id[i]);
if (sound) {
sound._volume = vol;
if (self._webAudio && sound._node) {
sound._node.gain.setValueAtTime(vol * Howler.volume(), ctx.currentTime);
} else if (sound._node) {
sound._node.volume = vol * Howler.volume();
}
}
}
} else {
sound = id ? self._soundById(id) : self._sounds[0];
return sound ? sound._volume : 0;
}
return self;
},
/**
* Fade a currently playing sound between two volumes (if no id is passsed, all sounds will fade).
* @param {Number} from The value 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 {Number} id The sound id (omit to fade all sounds).
* @return {Howl}
*/
fade: function(from, to, len, id) {
var self = this;
// Wait for the sound to play before fading.
if (!self._loaded) {
self.once('play', function() {
self.fade(from, to, len, id);
});
return self;
}
// Set the volume to the start position.
self.volume(from, id);
// Fade the volume of one or all sounds.
var ids = self._getSoundIds(id);
for (var i=0; i<ids.length; i++) {
// Get the sound.
var sound = self._soundById(ids[i]);
// Create a linear fade or fall back to timeouts with HTML5 Audio.
if (sound) {
if (self._webAudio) {
var currentTime = ctx.currentTime;
var end = currentTime + (len / 1000);
sound._volume = from;
sound._node.gain.setValueAtTime(from, currentTime);
sound._node.gain.linearRampToValueAtTime(to, end);
// Fire the event when complete.
setTimeout(function(id, sound) {
setTimeout(function() {
sound._volume = to;
self._emit('faded', id);
}, end - ctx.currentTime > 0 ? Math.ceil((end - ctx.currentTime) * 1000) : 0);
}.bind(self, ids[i], sound), len);
} else {
var diff = Math.abs(from - to);
var dir = from > to ? 'out' : 'in';
var steps = diff / 0.01;
var stepLen = len / steps;
(function() {
var vol = from;
var interval = setInterval(function(id) {
// Update the volume amount.
vol += (dir === 'in' ? 0.01 : -0.01);
// Make sure the volume is in the right bounds.
vol = Math.max(0, vol);
vol = Math.min(1, vol);
// Round to within 2 decimal points.
vol = Math.round(vol * 100) / 100;
// Change the volume.
self.volume(vol, id);
// When the fade is complete, stop it and fire event.
if (vol === to) {
clearInterval(interval);
self._emit('faded', id);
}
}.bind(self, ids[i]), stepLen);
})();
}
}
}
return self;
},
/**
* Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
* loop() -> Returns the group's loop value.
* loop(id) -> Returns the sound id's loop value.
* loop(loop) -> Sets the loop value for all sounds in this Howl group.
* loop(loop, id) -> Sets the loop value of passed sound id.
* @return {Howl/Boolean} Returns self or current loop value.
*/
loop: function() {
var self = this;
var args = arguments;
var loop, id, sound;
// Determine the values for loop and id.
if (args.length === 0) {
// Return the grou's loop value.
return self._loop;
} else if (args.length === 1) {
if (typeof args[0] === 'boolean') {
loop = args[0];
self._loop = loop;
} else {
// Return this sound's loop value.
sound = self._soundById(parseInt(args[0], 10));
return sound ? sound._loop : false;
}
} else if (args.length === 2) {
loop = args[0];
id = parseInt(args[1], 10);
}
// If no id is passed, get all ID's to be looped.
var ids = self._getSoundIds(id);
for (var i=0; i<ids.length; i++) {
sound = self._soundById(ids[i]);
if (sound) {
sound._loop = loop;
if (self._webAudio && sound._node) {
sound._node.bufferSource.loop = loop;
}
}
}
return self;
},
/**
* Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
* seek() -> Returns the first sound node's current seek position.
* seek(id) -> Returns the sound id's current seek position.
* seek(seek) -> Sets the seek position of the first sound node.
* seek(seek, id) -> Sets the seek position of passed sound id.
* @return {Howl/Number} Returns self or the current seek position.
*/
seek: function() {
var self = this;
var args = arguments;
var seek, id;
// Determine the values based on arguments.
if (args.length === 0) {
// We will simply return the current position of the first node.
id = self._sounds[0]._id;
} else if (args.length === 1) {
// First check if this is an ID, and if not, assume it is a new seek position.
var ids = self._getSoundIds();
var index = ids.indexOf(args[0]);
if (index >= 0) {
id = parseInt(args[0], 10);
} else {
id = self._sounds[0]._id;
seek = parseFloat(args[0]);
}
} else if (args.length === 2) {
seek = parseFloat(args[0]);
id = parseInt(args[1], 10);
}
// If there is no ID, bail out.
if (typeof id === 'undefined') {
return self;
}
// Wait for the sound to load before seeking it.
if (!self._loaded) {
self.once('load', function() {
self.seek.apply(self, args);
});
return self;
}
// Get the sound.
var sound = self._soundById(id);
if (sound) {
if (seek >= 0) {
// Pause the sound and update position for restarting playback.
var playing = self.playing(id);
if (playing) {
self.pause(id, true);
}
// Move the position of the track and cancel timer.
sound._seek = seek;
self._clearTimer(id);
// Restart the playback if the sound was playing.
if (playing) {
self.play(id, true);
}
} else {
if (self._webAudio) {
return (sound._seek + self.playing(id) ? ctx.currentTime - sound._playStart : 0);