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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
|
/*!
* howler.js v1.1.28
* howlerjs.com
*
* (c) 2013-2015, 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('touchend', unlock, false);
}
}, 0);
};
// setup a touch start listener to attempt an unlock in
window.addEventListener('touchend', 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') {
loop ? node.bufferSource.noteGrainOn(0, pos, 86400) : node.bufferSource.noteGrainOn(0, pos, duration);
} else {
loop ? node.bufferSource.start(0, pos, 86400) : 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();
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];
// listen for the correct load event and fire the callback
var listenerEvent = navigator.isCocoonJS ? 'canplaythrough' : 'loadedmetadata';
var listener = function() {
newNode.removeEventListener(listenerEvent, listener, false);
callback(newNode);
};
newNode.addEventListener(listenerEvent, listener, false);
}
},
/**
* 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 {String} soundId The play instance ID.
*/
_clearEndTimer: function(soundId) {
var self = this,
index = 0;
// loop through the timers to find the one associated with this sound
for (var i=0; i<self._onendTimer.length; i++) {
if (self._onendTimer[i].id === soundId) {
index = i;
break;
}
}
var timer = self._onendTimer[index];
if (timer) {
clearTimeout(timer.timer);
self._onendTimer.splice(index, 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.panningModel = self._model || 'equalpower';
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') {
events.push(fn);
} else {
for (var i=0; i<events.length; i++) {
if (fn) {
events[i].call(self, fn);
} else {
events[i].call(self);
}
}
}
return self;
},
/**
* Remove a custom event.
* @param {String} event Event type.
* @param {Function} fn Listener to remove.
* @return {Howl}
*/
off: function(event, fn) {
var self = this,
events = self['_on' + event],
fnString = fn ? fn.toString() : null;
if (fnString) {
// loop through functions in the event for comparison
for (var i=0; i<events.length; i++) {
if (fnString === events[i].toString()) {
events.splice(i, 1);
break;
}
}
} else {
self['_on' + event] = [];
}
return self;
},
/**
* Unload and destroy the current Howl object.
* This will immediately stop all play instances attached to this sound.
*/
unload: function() {
var self = this;
// stop playing any active nodes
var nodes = self._audioNode;
for (var i=0; i<self._audioNode.length; i++) {
// stop the sound if it is currently playing
if (!nodes[i].paused) {
self.stop(nodes[i].id);
self.on('end', nodes[i].id);
}
if (!self._webAudio) {
// remove the source if using HTML5 Audio
nodes[i].src = '';
} else {
// disconnect the output from the master gain
nodes[i].disconnect(0);
}
}
// make sure all timeouts are cleared
for (i=0; i<self._onendTimer.length; i++) {
clearTimeout(self._onendTimer[i].timer);
}
// remove the reference in the global Howler object
var index = Howler._howls.indexOf(self);
if (index !== null && index >= 0) {
Howler._howls.splice(index, 1);
}
// delete this sound from the cache
delete cache[self._src];
self = null;
}
};
// only define these functions when using WebAudio
if (usingWebAudio) {
/**
* Buffer a sound from URL (or from cache) and decode to audio source (Web Audio API).
* @param {Object} obj The Howl object for the sound to load.
* @param {String} url The path to the sound file.
*/
var loadBuffer = function(obj, url) {
// check if the buffer has already been cached
if (url in cache) {
// set the duration from the cache
obj._duration = cache[url].duration;
// load the sound into this object
loadSound(obj);
return;
}
if (/^data:[^;]+;base64,/.test(url)) {
// Decode base64 data-URIs because some browsers cannot load data-URIs with XMLHttpRequest.
var data = atob(url.split(',')[1]);
var dataView = new Uint8Array(data.length);
for (var i=0; i<data.length; ++i) {
dataView[i] = data.charCodeAt(i);
}
decodeAudioData(dataView.buffer, obj, url);
} else {
// load the buffer from the URL
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
decodeAudioData(xhr.response, obj, url);
};
xhr.onerror = function() {
// if there is an error, switch the sound to HTML Audio
if (obj._webAudio) {
obj._buffer = true;
obj._webAudio = false;
obj._audioNode = [];
delete obj._gainNode;
delete cache[url];
obj.load();
}
};
try {
xhr.send();
} catch (e) {
xhr.onerror();
}
}
};
/**
* Decode audio data from an array buffer.
* @param {ArrayBuffer} arraybuffer The audio data.
* @param {Object} obj The Howl object for the sound to load.
* @param {String} url The path to the sound file.
*/
var decodeAudioData = function(arraybuffer, obj, url) {
// decode the buffer into an audio source
ctx.decodeAudioData(
arraybuffer,
function(buffer) {
if (buffer) {
cache[url] = buffer;
loadSound(obj, buffer);
}
},
function(err) {
obj.on('loaderror');
}
);
};
/**
* Finishes loading the Web Audio API sound and fires the loaded event
* @param {Object} obj The Howl object for the sound to load.
* @param {Objecct} buffer The decoded buffer sound source.
*/
var loadSound = function(obj, buffer) {
// set the duration
obj._duration = (buffer) ? buffer.duration : obj._duration;
// setup a sprite if none is defined
if (Object.getOwnPropertyNames(obj._sprite).length === 0) {
obj._sprite = {_default: [0, obj._duration * 1000]};
}
// fire the loaded event
if (!obj._loaded) {
obj._loaded = true;
obj.on('load');
}
if (obj._autoplay) {
obj.play();
}
};
/**
* Load the sound back into the buffer source.
* @param {Object} obj The sound to load.
* @param {Array} loop Loop boolean, pos, and duration.
* @param {String} id (optional) The play instance ID.
*/
var refreshBuffer = function(obj, loop, id) {
// determine which node to connect to
var node = obj._nodeById(id);
// setup the buffer source for playback
node.bufferSource = ctx.createBufferSource();
node.bufferSource.buffer = cache[obj._src];
node.bufferSource.connect(node.panner);
node.bufferSource.loop = loop[0];
if (loop[0]) {
node.bufferSource.loopStart = loop[1];
node.bufferSource.loopEnd = loop[1] + loop[2];
}
node.bufferSource.playbackRate.value = obj._rate;
};
}
/**
* Add support for AMD (Asynchronous Module Definition) libraries such as require.js.
*/
if (typeof define === 'function' && define.amd) {
define(function() {
return {
Howler: Howler,
Howl: Howl
};
});
}
/**
* Add support for CommonJS libraries such as browserify.
*/
if (typeof exports !== 'undefined') {
exports.Howler = Howler;
exports.Howl = Howl;
}
// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined') {
window.Howler = Howler;
window.Howl = Howl;
}
})();
|