howler.core.js 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587
  1. /*!
  2. * howler.js v2.2.4
  3. * howlerjs.com
  4. *
  5. * (c) 2013-2020, James Simpson of GoldFire Studios
  6. * goldfirestudios.com
  7. *
  8. * MIT License
  9. */
  10. (function() {
  11. 'use strict';
  12. /** Global Methods **/
  13. /***************************************************************************/
  14. /**
  15. * Create the global controller. All contained methods and properties apply
  16. * to all sounds that are currently playing or will be in the future.
  17. */
  18. var HowlerGlobal = function() {
  19. this.init();
  20. };
  21. HowlerGlobal.prototype = {
  22. /**
  23. * Initialize the global Howler object.
  24. * @return {Howler}
  25. */
  26. init: function() {
  27. var self = this || Howler;
  28. // Create a global ID counter.
  29. self._counter = 1000;
  30. // Pool of unlocked HTML5 Audio objects.
  31. self._html5AudioPool = [];
  32. self.html5PoolSize = 10;
  33. // Internal properties.
  34. self._codecs = {};
  35. self._howls = [];
  36. self._muted = false;
  37. self._volume = 1;
  38. self._canPlayEvent = 'canplaythrough';
  39. self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null;
  40. // Public properties.
  41. self.masterGain = null;
  42. self.noAudio = false;
  43. self.usingWebAudio = true;
  44. self.autoSuspend = true;
  45. self.ctx = null;
  46. // Set to false to disable the auto audio unlocker.
  47. self.autoUnlock = true;
  48. // Setup the various state values for global tracking.
  49. self._setup();
  50. return self;
  51. },
  52. /**
  53. * Get/set the global volume for all sounds.
  54. * @param {Float} vol Volume from 0.0 to 1.0.
  55. * @return {Howler/Float} Returns self or current volume.
  56. */
  57. volume: function(vol) {
  58. var self = this || Howler;
  59. vol = parseFloat(vol);
  60. // If we don't have an AudioContext created yet, run the setup.
  61. if (!self.ctx) {
  62. setupAudioContext();
  63. }
  64. if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
  65. self._volume = vol;
  66. // Don't update any of the nodes if we are muted.
  67. if (self._muted) {
  68. return self;
  69. }
  70. // When using Web Audio, we just need to adjust the master gain.
  71. if (self.usingWebAudio) {
  72. self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime);
  73. }
  74. // Loop through and change volume for all HTML5 audio nodes.
  75. for (var i=0; i<self._howls.length; i++) {
  76. if (!self._howls[i]._webAudio) {
  77. // Get all of the sounds in this Howl group.
  78. var ids = self._howls[i]._getSoundIds();
  79. // Loop through all sounds and change the volumes.
  80. for (var j=0; j<ids.length; j++) {
  81. var sound = self._howls[i]._soundById(ids[j]);
  82. if (sound && sound._node) {
  83. sound._node.volume = sound._volume * vol;
  84. }
  85. }
  86. }
  87. }
  88. return self;
  89. }
  90. return self._volume;
  91. },
  92. /**
  93. * Handle muting and unmuting globally.
  94. * @param {Boolean} muted Is muted or not.
  95. */
  96. mute: function(muted) {
  97. var self = this || Howler;
  98. // If we don't have an AudioContext created yet, run the setup.
  99. if (!self.ctx) {
  100. setupAudioContext();
  101. }
  102. self._muted = muted;
  103. // With Web Audio, we just need to mute the master gain.
  104. if (self.usingWebAudio) {
  105. self.masterGain.gain.setValueAtTime(muted ? 0 : self._volume, Howler.ctx.currentTime);
  106. }
  107. // Loop through and mute all HTML5 Audio nodes.
  108. for (var i=0; i<self._howls.length; i++) {
  109. if (!self._howls[i]._webAudio) {
  110. // Get all of the sounds in this Howl group.
  111. var ids = self._howls[i]._getSoundIds();
  112. // Loop through all sounds and mark the audio node as muted.
  113. for (var j=0; j<ids.length; j++) {
  114. var sound = self._howls[i]._soundById(ids[j]);
  115. if (sound && sound._node) {
  116. sound._node.muted = (muted) ? true : sound._muted;
  117. }
  118. }
  119. }
  120. }
  121. return self;
  122. },
  123. /**
  124. * Handle stopping all sounds globally.
  125. */
  126. stop: function() {
  127. var self = this || Howler;
  128. // Loop through all Howls and stop them.
  129. for (var i=0; i<self._howls.length; i++) {
  130. self._howls[i].stop();
  131. }
  132. return self;
  133. },
  134. /**
  135. * Unload and destroy all currently loaded Howl objects.
  136. * @return {Howler}
  137. */
  138. unload: function() {
  139. var self = this || Howler;
  140. for (var i=self._howls.length-1; i>=0; i--) {
  141. self._howls[i].unload();
  142. }
  143. // Create a new AudioContext to make sure it is fully reset.
  144. if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') {
  145. self.ctx.close();
  146. self.ctx = null;
  147. setupAudioContext();
  148. }
  149. return self;
  150. },
  151. /**
  152. * Check for codec support of specific extension.
  153. * @param {String} ext Audio file extention.
  154. * @return {Boolean}
  155. */
  156. codecs: function(ext) {
  157. return (this || Howler)._codecs[ext.replace(/^x-/, '')];
  158. },
  159. /**
  160. * Setup various state values for global tracking.
  161. * @return {Howler}
  162. */
  163. _setup: function() {
  164. var self = this || Howler;
  165. // Keeps track of the suspend/resume state of the AudioContext.
  166. self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended';
  167. // Automatically begin the 30-second suspend process
  168. self._autoSuspend();
  169. // Check if audio is available.
  170. if (!self.usingWebAudio) {
  171. // No audio is available on this system if noAudio is set to true.
  172. if (typeof Audio !== 'undefined') {
  173. try {
  174. var test = new Audio();
  175. // Check if the canplaythrough event is available.
  176. if (typeof test.oncanplaythrough === 'undefined') {
  177. self._canPlayEvent = 'canplay';
  178. }
  179. } catch(e) {
  180. self.noAudio = true;
  181. }
  182. } else {
  183. self.noAudio = true;
  184. }
  185. }
  186. // Test to make sure audio isn't disabled in Internet Explorer.
  187. try {
  188. var test = new Audio();
  189. if (test.muted) {
  190. self.noAudio = true;
  191. }
  192. } catch (e) {}
  193. // Check for supported codecs.
  194. if (!self.noAudio) {
  195. self._setupCodecs();
  196. }
  197. return self;
  198. },
  199. /**
  200. * Check for browser support for various codecs and cache the results.
  201. * @return {Howler}
  202. */
  203. _setupCodecs: function() {
  204. var self = this || Howler;
  205. var audioTest = null;
  206. // Must wrap in a try/catch because IE11 in server mode throws an error.
  207. try {
  208. audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
  209. } catch (err) {
  210. return self;
  211. }
  212. if (!audioTest || typeof audioTest.canPlayType !== 'function') {
  213. return self;
  214. }
  215. var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
  216. // Opera version <33 has mixed MP3 support, so we need to check for and block it.
  217. var ua = self._navigator ? self._navigator.userAgent : '';
  218. var checkOpera = ua.match(/OPR\/(\d+)/g);
  219. var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);
  220. var checkSafari = ua.indexOf('Safari') !== -1 && ua.indexOf('Chrome') === -1;
  221. var safariVersion = ua.match(/Version\/(.*?) /);
  222. var isOldSafari = (checkSafari && safariVersion && parseInt(safariVersion[1], 10) < 15);
  223. self._codecs = {
  224. mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
  225. mpeg: !!mpegTest,
  226. opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
  227. ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
  228. oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
  229. wav: !!(audioTest.canPlayType('audio/wav; codecs="1"') || audioTest.canPlayType('audio/wav')).replace(/^no$/, ''),
  230. aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
  231. caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
  232. m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
  233. m4b: !!(audioTest.canPlayType('audio/x-m4b;') || audioTest.canPlayType('audio/m4b;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
  234. mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
  235. weba: !!(!isOldSafari && audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')),
  236. webm: !!(!isOldSafari && audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')),
  237. dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
  238. flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
  239. };
  240. return self;
  241. },
  242. /**
  243. * Some browsers/devices will only allow audio to be played after a user interaction.
  244. * Attempt to automatically unlock audio on the first user interaction.
  245. * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
  246. * @return {Howler}
  247. */
  248. _unlockAudio: function() {
  249. var self = this || Howler;
  250. // Only run this if Web Audio is supported and it hasn't already been unlocked.
  251. if (self._audioUnlocked || !self.ctx) {
  252. return;
  253. }
  254. self._audioUnlocked = false;
  255. self.autoUnlock = false;
  256. // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views.
  257. // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000.
  258. // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate.
  259. if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) {
  260. self._mobileUnloaded = true;
  261. self.unload();
  262. }
  263. // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per:
  264. // http://stackoverflow.com/questions/24119684
  265. self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050);
  266. // Call this method on touch start to create and play a buffer,
  267. // then check if the audio actually played to determine if
  268. // audio has now been unlocked on iOS, Android, etc.
  269. var unlock = function(e) {
  270. // Create a pool of unlocked HTML5 Audio objects that can
  271. // be used for playing sounds without user interaction. HTML5
  272. // Audio objects must be individually unlocked, as opposed
  273. // to the WebAudio API which only needs a single activation.
  274. // This must occur before WebAudio setup or the source.onended
  275. // event will not fire.
  276. while (self._html5AudioPool.length < self.html5PoolSize) {
  277. try {
  278. var audioNode = new Audio();
  279. // Mark this Audio object as unlocked to ensure it can get returned
  280. // to the unlocked pool when released.
  281. audioNode._unlocked = true;
  282. // Add the audio node to the pool.
  283. self._releaseHtml5Audio(audioNode);
  284. } catch (e) {
  285. self.noAudio = true;
  286. break;
  287. }
  288. }
  289. // Loop through any assigned audio nodes and unlock them.
  290. for (var i=0; i<self._howls.length; i++) {
  291. if (!self._howls[i]._webAudio) {
  292. // Get all of the sounds in this Howl group.
  293. var ids = self._howls[i]._getSoundIds();
  294. // Loop through all sounds and unlock the audio nodes.
  295. for (var j=0; j<ids.length; j++) {
  296. var sound = self._howls[i]._soundById(ids[j]);
  297. if (sound && sound._node && !sound._node._unlocked) {
  298. sound._node._unlocked = true;
  299. sound._node.load();
  300. }
  301. }
  302. }
  303. }
  304. // Fix Android can not play in suspend state.
  305. self._autoResume();
  306. // Create an empty buffer.
  307. var source = self.ctx.createBufferSource();
  308. source.buffer = self._scratchBuffer;
  309. source.connect(self.ctx.destination);
  310. // Play the empty buffer.
  311. if (typeof source.start === 'undefined') {
  312. source.noteOn(0);
  313. } else {
  314. source.start(0);
  315. }
  316. // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
  317. if (typeof self.ctx.resume === 'function') {
  318. self.ctx.resume();
  319. }
  320. // Setup a timeout to check that we are unlocked on the next event loop.
  321. source.onended = function() {
  322. source.disconnect(0);
  323. // Update the unlocked state and prevent this check from happening again.
  324. self._audioUnlocked = true;
  325. // Remove the touch start listener.
  326. document.removeEventListener('touchstart', unlock, true);
  327. document.removeEventListener('touchend', unlock, true);
  328. document.removeEventListener('click', unlock, true);
  329. document.removeEventListener('keydown', unlock, true);
  330. // Let all sounds know that audio has been unlocked.
  331. for (var i=0; i<self._howls.length; i++) {
  332. self._howls[i]._emit('unlock');
  333. }
  334. };
  335. };
  336. // Setup a touch start listener to attempt an unlock in.
  337. document.addEventListener('touchstart', unlock, true);
  338. document.addEventListener('touchend', unlock, true);
  339. document.addEventListener('click', unlock, true);
  340. document.addEventListener('keydown', unlock, true);
  341. return self;
  342. },
  343. /**
  344. * Get an unlocked HTML5 Audio object from the pool. If none are left,
  345. * return a new Audio object and throw a warning.
  346. * @return {Audio} HTML5 Audio object.
  347. */
  348. _obtainHtml5Audio: function() {
  349. var self = this || Howler;
  350. // Return the next object from the pool if one exists.
  351. if (self._html5AudioPool.length) {
  352. return self._html5AudioPool.pop();
  353. }
  354. //.Check if the audio is locked and throw a warning.
  355. var testPlay = new Audio().play();
  356. if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) {
  357. testPlay.catch(function() {
  358. console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.');
  359. });
  360. }
  361. return new Audio();
  362. },
  363. /**
  364. * Return an activated HTML5 Audio object to the pool.
  365. * @return {Howler}
  366. */
  367. _releaseHtml5Audio: function(audio) {
  368. var self = this || Howler;
  369. // Don't add audio to the pool if we don't know if it has been unlocked.
  370. if (audio._unlocked) {
  371. self._html5AudioPool.push(audio);
  372. }
  373. return self;
  374. },
  375. /**
  376. * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
  377. * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
  378. * @return {Howler}
  379. */
  380. _autoSuspend: function() {
  381. var self = this;
  382. if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) {
  383. return;
  384. }
  385. // Check if any sounds are playing.
  386. for (var i=0; i<self._howls.length; i++) {
  387. if (self._howls[i]._webAudio) {
  388. for (var j=0; j<self._howls[i]._sounds.length; j++) {
  389. if (!self._howls[i]._sounds[j]._paused) {
  390. return self;
  391. }
  392. }
  393. }
  394. }
  395. if (self._suspendTimer) {
  396. clearTimeout(self._suspendTimer);
  397. }
  398. // If no sound has played after 30 seconds, suspend the context.
  399. self._suspendTimer = setTimeout(function() {
  400. if (!self.autoSuspend) {
  401. return;
  402. }
  403. self._suspendTimer = null;
  404. self.state = 'suspending';
  405. // Handle updating the state of the audio context after suspending.
  406. var handleSuspension = function() {
  407. self.state = 'suspended';
  408. if (self._resumeAfterSuspend) {
  409. delete self._resumeAfterSuspend;
  410. self._autoResume();
  411. }
  412. };
  413. // Either the state gets suspended or it is interrupted.
  414. // Either way, we need to update the state to suspended.
  415. self.ctx.suspend().then(handleSuspension, handleSuspension);
  416. }, 30000);
  417. return self;
  418. },
  419. /**
  420. * Automatically resume the Web Audio AudioContext when a new sound is played.
  421. * @return {Howler}
  422. */
  423. _autoResume: function() {
  424. var self = this;
  425. if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) {
  426. return;
  427. }
  428. if (self.state === 'running' && self.ctx.state !== 'interrupted' && self._suspendTimer) {
  429. clearTimeout(self._suspendTimer);
  430. self._suspendTimer = null;
  431. } else if (self.state === 'suspended' || self.state === 'running' && self.ctx.state === 'interrupted') {
  432. self.ctx.resume().then(function() {
  433. self.state = 'running';
  434. // Emit to all Howls that the audio has resumed.
  435. for (var i=0; i<self._howls.length; i++) {
  436. self._howls[i]._emit('resume');
  437. }
  438. });
  439. if (self._suspendTimer) {
  440. clearTimeout(self._suspendTimer);
  441. self._suspendTimer = null;
  442. }
  443. } else if (self.state === 'suspending') {
  444. self._resumeAfterSuspend = true;
  445. }
  446. return self;
  447. }
  448. };
  449. // Setup the global audio controller.
  450. var Howler = new HowlerGlobal();
  451. /** Group Methods **/
  452. /***************************************************************************/
  453. /**
  454. * Create an audio group controller.
  455. * @param {Object} o Passed in properties for this group.
  456. */
  457. var Howl = function(o) {
  458. var self = this;
  459. // Throw an error if no source is provided.
  460. if (!o.src || o.src.length === 0) {
  461. console.error('An array of source files must be passed with any new Howl.');
  462. return;
  463. }
  464. self.init(o);
  465. };
  466. Howl.prototype = {
  467. /**
  468. * Initialize a new Howl group object.
  469. * @param {Object} o Passed in properties for this group.
  470. * @return {Howl}
  471. */
  472. init: function(o) {
  473. var self = this;
  474. // If we don't have an AudioContext created yet, run the setup.
  475. if (!Howler.ctx) {
  476. setupAudioContext();
  477. }
  478. // Setup user-defined default properties.
  479. self._autoplay = o.autoplay || false;
  480. self._format = (typeof o.format !== 'string') ? o.format : [o.format];
  481. self._html5 = o.html5 || false;
  482. self._muted = o.mute || false;
  483. self._loop = o.loop || false;
  484. self._pool = o.pool || 5;
  485. self._preload = (typeof o.preload === 'boolean' || o.preload === 'metadata') ? o.preload : true;
  486. self._rate = o.rate || 1;
  487. self._sprite = o.sprite || {};
  488. self._src = (typeof o.src !== 'string') ? o.src : [o.src];
  489. self._volume = o.volume !== undefined ? o.volume : 1;
  490. self._xhr = {
  491. method: o.xhr && o.xhr.method ? o.xhr.method : 'GET',
  492. headers: o.xhr && o.xhr.headers ? o.xhr.headers : null,
  493. withCredentials: o.xhr && o.xhr.withCredentials ? o.xhr.withCredentials : false,
  494. };
  495. // Setup all other default properties.
  496. self._duration = 0;
  497. self._state = 'unloaded';
  498. self._sounds = [];
  499. self._endTimers = {};
  500. self._queue = [];
  501. self._playLock = false;
  502. // Setup event listeners.
  503. self._onend = o.onend ? [{fn: o.onend}] : [];
  504. self._onfade = o.onfade ? [{fn: o.onfade}] : [];
  505. self._onload = o.onload ? [{fn: o.onload}] : [];
  506. self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
  507. self._onplayerror = o.onplayerror ? [{fn: o.onplayerror}] : [];
  508. self._onpause = o.onpause ? [{fn: o.onpause}] : [];
  509. self._onplay = o.onplay ? [{fn: o.onplay}] : [];
  510. self._onstop = o.onstop ? [{fn: o.onstop}] : [];
  511. self._onmute = o.onmute ? [{fn: o.onmute}] : [];
  512. self._onvolume = o.onvolume ? [{fn: o.onvolume}] : [];
  513. self._onrate = o.onrate ? [{fn: o.onrate}] : [];
  514. self._onseek = o.onseek ? [{fn: o.onseek}] : [];
  515. self._onunlock = o.onunlock ? [{fn: o.onunlock}] : [];
  516. self._onresume = [];
  517. // Web Audio or HTML5 Audio?
  518. self._webAudio = Howler.usingWebAudio && !self._html5;
  519. // Automatically try to enable audio.
  520. if (typeof Howler.ctx !== 'undefined' && Howler.ctx && Howler.autoUnlock) {
  521. Howler._unlockAudio();
  522. }
  523. // Keep track of this Howl group in the global controller.
  524. Howler._howls.push(self);
  525. // If they selected autoplay, add a play event to the load queue.
  526. if (self._autoplay) {
  527. self._queue.push({
  528. event: 'play',
  529. action: function() {
  530. self.play();
  531. }
  532. });
  533. }
  534. // Load the source file unless otherwise specified.
  535. if (self._preload && self._preload !== 'none') {
  536. self.load();
  537. }
  538. return self;
  539. },
  540. /**
  541. * Load the audio file.
  542. * @return {Howler}
  543. */
  544. load: function() {
  545. var self = this;
  546. var url = null;
  547. // If no audio is available, quit immediately.
  548. if (Howler.noAudio) {
  549. self._emit('loaderror', null, 'No audio support.');
  550. return;
  551. }
  552. // Make sure our source is in an array.
  553. if (typeof self._src === 'string') {
  554. self._src = [self._src];
  555. }
  556. // Loop through the sources and pick the first one that is compatible.
  557. for (var i=0; i<self._src.length; i++) {
  558. var ext, str;
  559. if (self._format && self._format[i]) {
  560. // If an extension was specified, use that instead.
  561. ext = self._format[i];
  562. } else {
  563. // Make sure the source is a string.
  564. str = self._src[i];
  565. if (typeof str !== 'string') {
  566. self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.');
  567. continue;
  568. }
  569. // Extract the file extension from the URL or base64 data URI.
  570. ext = /^data:audio\/([^;,]+);/i.exec(str);
  571. if (!ext) {
  572. ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]);
  573. }
  574. if (ext) {
  575. ext = ext[1].toLowerCase();
  576. }
  577. }
  578. // Log a warning if no extension was found.
  579. if (!ext) {
  580. console.warn('No file extension was found. Consider using the "format" property or specify an extension.');
  581. }
  582. // Check if this extension is available.
  583. if (ext && Howler.codecs(ext)) {
  584. url = self._src[i];
  585. break;
  586. }
  587. }
  588. if (!url) {
  589. self._emit('loaderror', null, 'No codec support for selected audio sources.');
  590. return;
  591. }
  592. self._src = url;
  593. self._state = 'loading';
  594. // If the hosting page is HTTPS and the source isn't,
  595. // drop down to HTML5 Audio to avoid Mixed Content errors.
  596. if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') {
  597. self._html5 = true;
  598. self._webAudio = false;
  599. }
  600. // Create a new sound object and add it to the pool.
  601. new Sound(self);
  602. // Load and decode the audio data for playback.
  603. if (self._webAudio) {
  604. loadBuffer(self);
  605. }
  606. return self;
  607. },
  608. /**
  609. * Play a sound or resume previous playback.
  610. * @param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
  611. * @param {Boolean} internal Internal Use: true prevents event firing.
  612. * @return {Number} Sound ID.
  613. */
  614. play: function(sprite, internal) {
  615. var self = this;
  616. var id = null;
  617. // Determine if a sprite, sound id or nothing was passed
  618. if (typeof sprite === 'number') {
  619. id = sprite;
  620. sprite = null;
  621. } else if (typeof sprite === 'string' && self._state === 'loaded' && !self._sprite[sprite]) {
  622. // If the passed sprite doesn't exist, do nothing.
  623. return null;
  624. } else if (typeof sprite === 'undefined') {
  625. // Use the default sound sprite (plays the full audio length).
  626. sprite = '__default';
  627. // Check if there is a single paused sound that isn't ended.
  628. // If there is, play that sound. If not, continue as usual.
  629. if (!self._playLock) {
  630. var num = 0;
  631. for (var i=0; i<self._sounds.length; i++) {
  632. if (self._sounds[i]._paused && !self._sounds[i]._ended) {
  633. num++;
  634. id = self._sounds[i]._id;
  635. }
  636. }
  637. if (num === 1) {
  638. sprite = null;
  639. } else {
  640. id = null;
  641. }
  642. }
  643. }
  644. // Get the selected node, or get one from the pool.
  645. var sound = id ? self._soundById(id) : self._inactiveSound();
  646. // If the sound doesn't exist, do nothing.
  647. if (!sound) {
  648. return null;
  649. }
  650. // Select the sprite definition.
  651. if (id && !sprite) {
  652. sprite = sound._sprite || '__default';
  653. }
  654. // If the sound hasn't loaded, we must wait to get the audio's duration.
  655. // We also need to wait to make sure we don't run into race conditions with
  656. // the order of function calls.
  657. if (self._state !== 'loaded') {
  658. // Set the sprite value on this sound.
  659. sound._sprite = sprite;
  660. // Mark this sound as not ended in case another sound is played before this one loads.
  661. sound._ended = false;
  662. // Add the sound to the queue to be played on load.
  663. var soundId = sound._id;
  664. self._queue.push({
  665. event: 'play',
  666. action: function() {
  667. self.play(soundId);
  668. }
  669. });
  670. return soundId;
  671. }
  672. // Don't play the sound if an id was passed and it is already playing.
  673. if (id && !sound._paused) {
  674. // Trigger the play event, in order to keep iterating through queue.
  675. if (!internal) {
  676. self._loadQueue('play');
  677. }
  678. return sound._id;
  679. }
  680. // Make sure the AudioContext isn't suspended, and resume it if it is.
  681. if (self._webAudio) {
  682. Howler._autoResume();
  683. }
  684. // Determine how long to play for and where to start playing.
  685. var seek = Math.max(0, sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000);
  686. var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek);
  687. var timeout = (duration * 1000) / Math.abs(sound._rate);
  688. var start = self._sprite[sprite][0] / 1000;
  689. var stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
  690. sound._sprite = sprite;
  691. // Mark the sound as ended instantly so that this async playback
  692. // doesn't get grabbed by another call to play while this one waits to start.
  693. sound._ended = false;
  694. // Update the parameters of the sound.
  695. var setParams = function() {
  696. sound._paused = false;
  697. sound._seek = seek;
  698. sound._start = start;
  699. sound._stop = stop;
  700. sound._loop = !!(sound._loop || self._sprite[sprite][2]);
  701. };
  702. // End the sound instantly if seek is at the end.
  703. if (seek >= stop) {
  704. self._ended(sound);
  705. return;
  706. }
  707. // Begin the actual playback.
  708. var node = sound._node;
  709. if (self._webAudio) {
  710. // Fire this when the sound is ready to play to begin Web Audio playback.
  711. var playWebAudio = function() {
  712. self._playLock = false;
  713. setParams();
  714. self._refreshBuffer(sound);
  715. // Setup the playback params.
  716. var vol = (sound._muted || self._muted) ? 0 : sound._volume;
  717. node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
  718. sound._playStart = Howler.ctx.currentTime;
  719. // Play the sound using the supported method.
  720. if (typeof node.bufferSource.start === 'undefined') {
  721. sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
  722. } else {
  723. sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
  724. }
  725. // Start a new timer if none is present.
  726. if (timeout !== Infinity) {
  727. self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
  728. }
  729. if (!internal) {
  730. setTimeout(function() {
  731. self._emit('play', sound._id);
  732. self._loadQueue();
  733. }, 0);
  734. }
  735. };
  736. if (Howler.state === 'running' && Howler.ctx.state !== 'interrupted') {
  737. playWebAudio();
  738. } else {
  739. self._playLock = true;
  740. // Wait for the audio context to resume before playing.
  741. self.once('resume', playWebAudio);
  742. // Cancel the end timer.
  743. self._clearTimer(sound._id);
  744. }
  745. } else {
  746. // Fire this when the sound is ready to play to begin HTML5 Audio playback.
  747. var playHtml5 = function() {
  748. node.currentTime = seek;
  749. node.muted = sound._muted || self._muted || Howler._muted || node.muted;
  750. node.volume = sound._volume * Howler.volume();
  751. node.playbackRate = sound._rate;
  752. // Some browsers will throw an error if this is called without user interaction.
  753. try {
  754. var play = node.play();
  755. // Support older browsers that don't support promises, and thus don't have this issue.
  756. if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
  757. // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
  758. self._playLock = true;
  759. // Set param values immediately.
  760. setParams();
  761. // Releases the lock and executes queued actions.
  762. play
  763. .then(function() {
  764. self._playLock = false;
  765. node._unlocked = true;
  766. if (!internal) {
  767. self._emit('play', sound._id);
  768. } else {
  769. self._loadQueue();
  770. }
  771. })
  772. .catch(function() {
  773. self._playLock = false;
  774. self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
  775. 'on mobile devices and Chrome where playback was not within a user interaction.');
  776. // Reset the ended and paused values.
  777. sound._ended = true;
  778. sound._paused = true;
  779. });
  780. } else if (!internal) {
  781. self._playLock = false;
  782. setParams();
  783. self._emit('play', sound._id);
  784. }
  785. // Setting rate before playing won't work in IE, so we set it again here.
  786. node.playbackRate = sound._rate;
  787. // If the node is still paused, then we can assume there was a playback issue.
  788. if (node.paused) {
  789. self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
  790. 'on mobile devices and Chrome where playback was not within a user interaction.');
  791. return;
  792. }
  793. // Setup the end timer on sprites or listen for the ended event.
  794. if (sprite !== '__default' || sound._loop) {
  795. self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
  796. } else {
  797. self._endTimers[sound._id] = function() {
  798. // Fire ended on this audio node.
  799. self._ended(sound);
  800. // Clear this listener.
  801. node.removeEventListener('ended', self._endTimers[sound._id], false);
  802. };
  803. node.addEventListener('ended', self._endTimers[sound._id], false);
  804. }
  805. } catch (err) {
  806. self._emit('playerror', sound._id, err);
  807. }
  808. };
  809. // If this is streaming audio, make sure the src is set and load again.
  810. if (node.src === 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA') {
  811. node.src = self._src;
  812. node.load();
  813. }
  814. // Play immediately if ready, or wait for the 'canplaythrough'e vent.
  815. var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS);
  816. if (node.readyState >= 3 || loadedNoReadyState) {
  817. playHtml5();
  818. } else {
  819. self._playLock = true;
  820. self._state = 'loading';
  821. var listener = function() {
  822. self._state = 'loaded';
  823. // Begin playback.
  824. playHtml5();
  825. // Clear this listener.
  826. node.removeEventListener(Howler._canPlayEvent, listener, false);
  827. };
  828. node.addEventListener(Howler._canPlayEvent, listener, false);
  829. // Cancel the end timer.
  830. self._clearTimer(sound._id);
  831. }
  832. }
  833. return sound._id;
  834. },
  835. /**
  836. * Pause playback and save current position.
  837. * @param {Number} id The sound ID (empty to pause all in group).
  838. * @return {Howl}
  839. */
  840. pause: function(id) {
  841. var self = this;
  842. // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable.
  843. if (self._state !== 'loaded' || self._playLock) {
  844. self._queue.push({
  845. event: 'pause',
  846. action: function() {
  847. self.pause(id);
  848. }
  849. });
  850. return self;
  851. }
  852. // If no id is passed, get all ID's to be paused.
  853. var ids = self._getSoundIds(id);
  854. for (var i=0; i<ids.length; i++) {
  855. // Clear the end timer.
  856. self._clearTimer(ids[i]);
  857. // Get the sound.
  858. var sound = self._soundById(ids[i]);
  859. if (sound && !sound._paused) {
  860. // Reset the seek position.
  861. sound._seek = self.seek(ids[i]);
  862. sound._rateSeek = 0;
  863. sound._paused = true;
  864. // Stop currently running fades.
  865. self._stopFade(ids[i]);
  866. if (sound._node) {
  867. if (self._webAudio) {
  868. // Make sure the sound has been created.
  869. if (!sound._node.bufferSource) {
  870. continue;
  871. }
  872. if (typeof sound._node.bufferSource.stop === 'undefined') {
  873. sound._node.bufferSource.noteOff(0);
  874. } else {
  875. sound._node.bufferSource.stop(0);
  876. }
  877. // Clean up the buffer source.
  878. self._cleanBuffer(sound._node);
  879. } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
  880. sound._node.pause();
  881. }
  882. }
  883. }
  884. // Fire the pause event, unless `true` is passed as the 2nd argument.
  885. if (!arguments[1]) {
  886. self._emit('pause', sound ? sound._id : null);
  887. }
  888. }
  889. return self;
  890. },
  891. /**
  892. * Stop playback and reset to start.
  893. * @param {Number} id The sound ID (empty to stop all in group).
  894. * @param {Boolean} internal Internal Use: true prevents event firing.
  895. * @return {Howl}
  896. */
  897. stop: function(id, internal) {
  898. var self = this;
  899. // If the sound hasn't loaded, add it to the load queue to stop when capable.
  900. if (self._state !== 'loaded' || self._playLock) {
  901. self._queue.push({
  902. event: 'stop',
  903. action: function() {
  904. self.stop(id);
  905. }
  906. });
  907. return self;
  908. }
  909. // If no id is passed, get all ID's to be stopped.
  910. var ids = self._getSoundIds(id);
  911. for (var i=0; i<ids.length; i++) {
  912. // Clear the end timer.
  913. self._clearTimer(ids[i]);
  914. // Get the sound.
  915. var sound = self._soundById(ids[i]);
  916. if (sound) {
  917. // Reset the seek position.
  918. sound._seek = sound._start || 0;
  919. sound._rateSeek = 0;
  920. sound._paused = true;
  921. sound._ended = true;
  922. // Stop currently running fades.
  923. self._stopFade(ids[i]);
  924. if (sound._node) {
  925. if (self._webAudio) {
  926. // Make sure the sound's AudioBufferSourceNode has been created.
  927. if (sound._node.bufferSource) {
  928. if (typeof sound._node.bufferSource.stop === 'undefined') {
  929. sound._node.bufferSource.noteOff(0);
  930. } else {
  931. sound._node.bufferSource.stop(0);
  932. }
  933. // Clean up the buffer source.
  934. self._cleanBuffer(sound._node);
  935. }
  936. } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
  937. sound._node.currentTime = sound._start || 0;
  938. sound._node.pause();
  939. // If this is a live stream, stop download once the audio is stopped.
  940. if (sound._node.duration === Infinity) {
  941. self._clearSound(sound._node);
  942. }
  943. }
  944. }
  945. if (!internal) {
  946. self._emit('stop', sound._id);
  947. }
  948. }
  949. }
  950. return self;
  951. },
  952. /**
  953. * Mute/unmute a single sound or all sounds in this Howl group.
  954. * @param {Boolean} muted Set to true to mute and false to unmute.
  955. * @param {Number} id The sound ID to update (omit to mute/unmute all).
  956. * @return {Howl}
  957. */
  958. mute: function(muted, id) {
  959. var self = this;
  960. // If the sound hasn't loaded, add it to the load queue to mute when capable.
  961. if (self._state !== 'loaded'|| self._playLock) {
  962. self._queue.push({
  963. event: 'mute',
  964. action: function() {
  965. self.mute(muted, id);
  966. }
  967. });
  968. return self;
  969. }
  970. // If applying mute/unmute to all sounds, update the group's value.
  971. if (typeof id === 'undefined') {
  972. if (typeof muted === 'boolean') {
  973. self._muted = muted;
  974. } else {
  975. return self._muted;
  976. }
  977. }
  978. // If no id is passed, get all ID's to be muted.
  979. var ids = self._getSoundIds(id);
  980. for (var i=0; i<ids.length; i++) {
  981. // Get the sound.
  982. var sound = self._soundById(ids[i]);
  983. if (sound) {
  984. sound._muted = muted;
  985. // Cancel active fade and set the volume to the end value.
  986. if (sound._interval) {
  987. self._stopFade(sound._id);
  988. }
  989. if (self._webAudio && sound._node) {
  990. sound._node.gain.setValueAtTime(muted ? 0 : sound._volume, Howler.ctx.currentTime);
  991. } else if (sound._node) {
  992. sound._node.muted = Howler._muted ? true : muted;
  993. }
  994. self._emit('mute', sound._id);
  995. }
  996. }
  997. return self;
  998. },
  999. /**
  1000. * Get/set the volume of this sound or of the Howl group. This method can optionally take 0, 1 or 2 arguments.
  1001. * volume() -> Returns the group's volume value.
  1002. * volume(id) -> Returns the sound id's current volume.
  1003. * volume(vol) -> Sets the volume of all sounds in this Howl group.
  1004. * volume(vol, id) -> Sets the volume of passed sound id.
  1005. * @return {Howl/Number} Returns self or current volume.
  1006. */
  1007. volume: function() {
  1008. var self = this;
  1009. var args = arguments;
  1010. var vol, id;
  1011. // Determine the values based on arguments.
  1012. if (args.length === 0) {
  1013. // Return the value of the groups' volume.
  1014. return self._volume;
  1015. } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') {
  1016. // First check if this is an ID, and if not, assume it is a new volume.
  1017. var ids = self._getSoundIds();
  1018. var index = ids.indexOf(args[0]);
  1019. if (index >= 0) {
  1020. id = parseInt(args[0], 10);
  1021. } else {
  1022. vol = parseFloat(args[0]);
  1023. }
  1024. } else if (args.length >= 2) {
  1025. vol = parseFloat(args[0]);
  1026. id = parseInt(args[1], 10);
  1027. }
  1028. // Update the volume or return the current volume.
  1029. var sound;
  1030. if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
  1031. // If the sound hasn't loaded, add it to the load queue to change volume when capable.
  1032. if (self._state !== 'loaded'|| self._playLock) {
  1033. self._queue.push({
  1034. event: 'volume',
  1035. action: function() {
  1036. self.volume.apply(self, args);
  1037. }
  1038. });
  1039. return self;
  1040. }
  1041. // Set the group volume.
  1042. if (typeof id === 'undefined') {
  1043. self._volume = vol;
  1044. }
  1045. // Update one or all volumes.
  1046. id = self._getSoundIds(id);
  1047. for (var i=0; i<id.length; i++) {
  1048. // Get the sound.
  1049. sound = self._soundById(id[i]);
  1050. if (sound) {
  1051. sound._volume = vol;
  1052. // Stop currently running fades.
  1053. if (!args[2]) {
  1054. self._stopFade(id[i]);
  1055. }
  1056. if (self._webAudio && sound._node && !sound._muted) {
  1057. sound._node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
  1058. } else if (sound._node && !sound._muted) {
  1059. sound._node.volume = vol * Howler.volume();
  1060. }
  1061. self._emit('volume', sound._id);
  1062. }
  1063. }
  1064. } else {
  1065. sound = id ? self._soundById(id) : self._sounds[0];
  1066. return sound ? sound._volume : 0;
  1067. }
  1068. return self;
  1069. },
  1070. /**
  1071. * Fade a currently playing sound between two volumes (if no id is passed, all sounds will fade).
  1072. * @param {Number} from The value to fade from (0.0 to 1.0).
  1073. * @param {Number} to The volume to fade to (0.0 to 1.0).
  1074. * @param {Number} len Time in milliseconds to fade.
  1075. * @param {Number} id The sound id (omit to fade all sounds).
  1076. * @return {Howl}
  1077. */
  1078. fade: function(from, to, len, id) {
  1079. var self = this;
  1080. // If the sound hasn't loaded, add it to the load queue to fade when capable.
  1081. if (self._state !== 'loaded' || self._playLock) {
  1082. self._queue.push({
  1083. event: 'fade',
  1084. action: function() {
  1085. self.fade(from, to, len, id);
  1086. }
  1087. });
  1088. return self;
  1089. }
  1090. // Make sure the to/from/len values are numbers.
  1091. from = Math.min(Math.max(0, parseFloat(from)), 1);
  1092. to = Math.min(Math.max(0, parseFloat(to)), 1);
  1093. len = parseFloat(len);
  1094. // Set the volume to the start position.
  1095. self.volume(from, id);
  1096. // Fade the volume of one or all sounds.
  1097. var ids = self._getSoundIds(id);
  1098. for (var i=0; i<ids.length; i++) {
  1099. // Get the sound.
  1100. var sound = self._soundById(ids[i]);
  1101. // Create a linear fade or fall back to timeouts with HTML5 Audio.
  1102. if (sound) {
  1103. // Stop the previous fade if no sprite is being used (otherwise, volume handles this).
  1104. if (!id) {
  1105. self._stopFade(ids[i]);
  1106. }
  1107. // If we are using Web Audio, let the native methods do the actual fade.
  1108. if (self._webAudio && !sound._muted) {
  1109. var currentTime = Howler.ctx.currentTime;
  1110. var end = currentTime + (len / 1000);
  1111. sound._volume = from;
  1112. sound._node.gain.setValueAtTime(from, currentTime);
  1113. sound._node.gain.linearRampToValueAtTime(to, end);
  1114. }
  1115. self._startFadeInterval(sound, from, to, len, ids[i], typeof id === 'undefined');
  1116. }
  1117. }
  1118. return self;
  1119. },
  1120. /**
  1121. * Starts the internal interval to fade a sound.
  1122. * @param {Object} sound Reference to sound to fade.
  1123. * @param {Number} from The value to fade from (0.0 to 1.0).
  1124. * @param {Number} to The volume to fade to (0.0 to 1.0).
  1125. * @param {Number} len Time in milliseconds to fade.
  1126. * @param {Number} id The sound id to fade.
  1127. * @param {Boolean} isGroup If true, set the volume on the group.
  1128. */
  1129. _startFadeInterval: function(sound, from, to, len, id, isGroup) {
  1130. var self = this;
  1131. var vol = from;
  1132. var diff = to - from;
  1133. var steps = Math.abs(diff / 0.01);
  1134. var stepLen = Math.max(4, (steps > 0) ? len / steps : len);
  1135. var lastTick = Date.now();
  1136. // Store the value being faded to.
  1137. sound._fadeTo = to;
  1138. // Update the volume value on each interval tick.
  1139. sound._interval = setInterval(function() {
  1140. // Update the volume based on the time since the last tick.
  1141. var tick = (Date.now() - lastTick) / len;
  1142. lastTick = Date.now();
  1143. vol += diff * tick;
  1144. // Round to within 2 decimal points.
  1145. vol = Math.round(vol * 100) / 100;
  1146. // Make sure the volume is in the right bounds.
  1147. if (diff < 0) {
  1148. vol = Math.max(to, vol);
  1149. } else {
  1150. vol = Math.min(to, vol);
  1151. }
  1152. // Change the volume.
  1153. if (self._webAudio) {
  1154. sound._volume = vol;
  1155. } else {
  1156. self.volume(vol, sound._id, true);
  1157. }
  1158. // Set the group's volume.
  1159. if (isGroup) {
  1160. self._volume = vol;
  1161. }
  1162. // When the fade is complete, stop it and fire event.
  1163. if ((to < from && vol <= to) || (to > from && vol >= to)) {
  1164. clearInterval(sound._interval);
  1165. sound._interval = null;
  1166. sound._fadeTo = null;
  1167. self.volume(to, sound._id);
  1168. self._emit('fade', sound._id);
  1169. }
  1170. }, stepLen);
  1171. },
  1172. /**
  1173. * Internal method that stops the currently playing fade when
  1174. * a new fade starts, volume is changed or the sound is stopped.
  1175. * @param {Number} id The sound id.
  1176. * @return {Howl}
  1177. */
  1178. _stopFade: function(id) {
  1179. var self = this;
  1180. var sound = self._soundById(id);
  1181. if (sound && sound._interval) {
  1182. if (self._webAudio) {
  1183. sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime);
  1184. }
  1185. clearInterval(sound._interval);
  1186. sound._interval = null;
  1187. self.volume(sound._fadeTo, id);
  1188. sound._fadeTo = null;
  1189. self._emit('fade', id);
  1190. }
  1191. return self;
  1192. },
  1193. /**
  1194. * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
  1195. * loop() -> Returns the group's loop value.
  1196. * loop(id) -> Returns the sound id's loop value.
  1197. * loop(loop) -> Sets the loop value for all sounds in this Howl group.
  1198. * loop(loop, id) -> Sets the loop value of passed sound id.
  1199. * @return {Howl/Boolean} Returns self or current loop value.
  1200. */
  1201. loop: function() {
  1202. var self = this;
  1203. var args = arguments;
  1204. var loop, id, sound;
  1205. // Determine the values for loop and id.
  1206. if (args.length === 0) {
  1207. // Return the grou's loop value.
  1208. return self._loop;
  1209. } else if (args.length === 1) {
  1210. if (typeof args[0] === 'boolean') {
  1211. loop = args[0];
  1212. self._loop = loop;
  1213. } else {
  1214. // Return this sound's loop value.
  1215. sound = self._soundById(parseInt(args[0], 10));
  1216. return sound ? sound._loop : false;
  1217. }
  1218. } else if (args.length === 2) {
  1219. loop = args[0];
  1220. id = parseInt(args[1], 10);
  1221. }
  1222. // If no id is passed, get all ID's to be looped.
  1223. var ids = self._getSoundIds(id);
  1224. for (var i=0; i<ids.length; i++) {
  1225. sound = self._soundById(ids[i]);
  1226. if (sound) {
  1227. sound._loop = loop;
  1228. if (self._webAudio && sound._node && sound._node.bufferSource) {
  1229. sound._node.bufferSource.loop = loop;
  1230. if (loop) {
  1231. sound._node.bufferSource.loopStart = sound._start || 0;
  1232. sound._node.bufferSource.loopEnd = sound._stop;
  1233. // If playing, restart playback to ensure looping updates.
  1234. if (self.playing(ids[i])) {
  1235. self.pause(ids[i], true);
  1236. self.play(ids[i], true);
  1237. }
  1238. }
  1239. }
  1240. }
  1241. }
  1242. return self;
  1243. },
  1244. /**
  1245. * Get/set the playback rate of a sound. This method can optionally take 0, 1 or 2 arguments.
  1246. * rate() -> Returns the first sound node's current playback rate.
  1247. * rate(id) -> Returns the sound id's current playback rate.
  1248. * rate(rate) -> Sets the playback rate of all sounds in this Howl group.
  1249. * rate(rate, id) -> Sets the playback rate of passed sound id.
  1250. * @return {Howl/Number} Returns self or the current playback rate.
  1251. */
  1252. rate: function() {
  1253. var self = this;
  1254. var args = arguments;
  1255. var rate, id;
  1256. // Determine the values based on arguments.
  1257. if (args.length === 0) {
  1258. // We will simply return the current rate of the first node.
  1259. id = self._sounds[0]._id;
  1260. } else if (args.length === 1) {
  1261. // First check if this is an ID, and if not, assume it is a new rate value.
  1262. var ids = self._getSoundIds();
  1263. var index = ids.indexOf(args[0]);
  1264. if (index >= 0) {
  1265. id = parseInt(args[0], 10);
  1266. } else {
  1267. rate = parseFloat(args[0]);
  1268. }
  1269. } else if (args.length === 2) {
  1270. rate = parseFloat(args[0]);
  1271. id = parseInt(args[1], 10);
  1272. }
  1273. // Update the playback rate or return the current value.
  1274. var sound;
  1275. if (typeof rate === 'number') {
  1276. // If the sound hasn't loaded, add it to the load queue to change playback rate when capable.
  1277. if (self._state !== 'loaded' || self._playLock) {
  1278. self._queue.push({
  1279. event: 'rate',
  1280. action: function() {
  1281. self.rate.apply(self, args);
  1282. }
  1283. });
  1284. return self;
  1285. }
  1286. // Set the group rate.
  1287. if (typeof id === 'undefined') {
  1288. self._rate = rate;
  1289. }
  1290. // Update one or all volumes.
  1291. id = self._getSoundIds(id);
  1292. for (var i=0; i<id.length; i++) {
  1293. // Get the sound.
  1294. sound = self._soundById(id[i]);
  1295. if (sound) {
  1296. // Keep track of our position when the rate changed and update the playback
  1297. // start position so we can properly adjust the seek position for time elapsed.
  1298. if (self.playing(id[i])) {
  1299. sound._rateSeek = self.seek(id[i]);
  1300. sound._playStart = self._webAudio ? Howler.ctx.currentTime : sound._playStart;
  1301. }
  1302. sound._rate = rate;
  1303. // Change the playback rate.
  1304. if (self._webAudio && sound._node && sound._node.bufferSource) {
  1305. sound._node.bufferSource.playbackRate.setValueAtTime(rate, Howler.ctx.currentTime);
  1306. } else if (sound._node) {
  1307. sound._node.playbackRate = rate;
  1308. }
  1309. // Reset the timers.
  1310. var seek = self.seek(id[i]);
  1311. var duration = ((self._sprite[sound._sprite][0] + self._sprite[sound._sprite][1]) / 1000) - seek;
  1312. var timeout = (duration * 1000) / Math.abs(sound._rate);
  1313. // Start a new end timer if sound is already playing.
  1314. if (self._endTimers[id[i]] || !sound._paused) {
  1315. self._clearTimer(id[i]);
  1316. self._endTimers[id[i]] = setTimeout(self._ended.bind(self, sound), timeout);
  1317. }
  1318. self._emit('rate', sound._id);
  1319. }
  1320. }
  1321. } else {
  1322. sound = self._soundById(id);
  1323. return sound ? sound._rate : self._rate;
  1324. }
  1325. return self;
  1326. },
  1327. /**
  1328. * Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
  1329. * seek() -> Returns the first sound node's current seek position.
  1330. * seek(id) -> Returns the sound id's current seek position.
  1331. * seek(seek) -> Sets the seek position of the first sound node.
  1332. * seek(seek, id) -> Sets the seek position of passed sound id.
  1333. * @return {Howl/Number} Returns self or the current seek position.
  1334. */
  1335. seek: function() {
  1336. var self = this;
  1337. var args = arguments;
  1338. var seek, id;
  1339. // Determine the values based on arguments.
  1340. if (args.length === 0) {
  1341. // We will simply return the current position of the first node.
  1342. if (self._sounds.length) {
  1343. id = self._sounds[0]._id;
  1344. }
  1345. } else if (args.length === 1) {
  1346. // First check if this is an ID, and if not, assume it is a new seek position.
  1347. var ids = self._getSoundIds();
  1348. var index = ids.indexOf(args[0]);
  1349. if (index >= 0) {
  1350. id = parseInt(args[0], 10);
  1351. } else if (self._sounds.length) {
  1352. id = self._sounds[0]._id;
  1353. seek = parseFloat(args[0]);
  1354. }
  1355. } else if (args.length === 2) {
  1356. seek = parseFloat(args[0]);
  1357. id = parseInt(args[1], 10);
  1358. }
  1359. // If there is no ID, bail out.
  1360. if (typeof id === 'undefined') {
  1361. return 0;
  1362. }
  1363. // If the sound hasn't loaded, add it to the load queue to seek when capable.
  1364. if (typeof seek === 'number' && (self._state !== 'loaded' || self._playLock)) {
  1365. self._queue.push({
  1366. event: 'seek',
  1367. action: function() {
  1368. self.seek.apply(self, args);
  1369. }
  1370. });
  1371. return self;
  1372. }
  1373. // Get the sound.
  1374. var sound = self._soundById(id);
  1375. if (sound) {
  1376. if (typeof seek === 'number' && seek >= 0) {
  1377. // Pause the sound and update position for restarting playback.
  1378. var playing = self.playing(id);
  1379. if (playing) {
  1380. self.pause(id, true);
  1381. }
  1382. // Move the position of the track and cancel timer.
  1383. sound._seek = seek;
  1384. sound._ended = false;
  1385. self._clearTimer(id);
  1386. // Update the seek position for HTML5 Audio.
  1387. if (!self._webAudio && sound._node && !isNaN(sound._node.duration)) {
  1388. sound._node.currentTime = seek;
  1389. }
  1390. // Seek and emit when ready.
  1391. var seekAndEmit = function() {
  1392. // Restart the playback if the sound was playing.
  1393. if (playing) {
  1394. self.play(id, true);
  1395. }
  1396. self._emit('seek', id);
  1397. };
  1398. // Wait for the play lock to be unset before emitting (HTML5 Audio).
  1399. if (playing && !self._webAudio) {
  1400. var emitSeek = function() {
  1401. if (!self._playLock) {
  1402. seekAndEmit();
  1403. } else {
  1404. setTimeout(emitSeek, 0);
  1405. }
  1406. };
  1407. setTimeout(emitSeek, 0);
  1408. } else {
  1409. seekAndEmit();
  1410. }
  1411. } else {
  1412. if (self._webAudio) {
  1413. var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0;
  1414. var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0;
  1415. return sound._seek + (rateSeek + realTime * Math.abs(sound._rate));
  1416. } else {
  1417. return sound._node.currentTime;
  1418. }
  1419. }
  1420. }
  1421. return self;
  1422. },
  1423. /**
  1424. * Check if a specific sound is currently playing or not (if id is provided), or check if at least one of the sounds in the group is playing or not.
  1425. * @param {Number} id The sound id to check. If none is passed, the whole sound group is checked.
  1426. * @return {Boolean} True if playing and false if not.
  1427. */
  1428. playing: function(id) {
  1429. var self = this;
  1430. // Check the passed sound ID (if any).
  1431. if (typeof id === 'number') {
  1432. var sound = self._soundById(id);
  1433. return sound ? !sound._paused : false;
  1434. }
  1435. // Otherwise, loop through all sounds and check if any are playing.
  1436. for (var i=0; i<self._sounds.length; i++) {
  1437. if (!self._sounds[i]._paused) {
  1438. return true;
  1439. }
  1440. }
  1441. return false;
  1442. },
  1443. /**
  1444. * Get the duration of this sound. Passing a sound id will return the sprite duration.
  1445. * @param {Number} id The sound id to check. If none is passed, return full source duration.
  1446. * @return {Number} Audio duration in seconds.
  1447. */
  1448. duration: function(id) {
  1449. var self = this;
  1450. var duration = self._duration;
  1451. // If we pass an ID, get the sound and return the sprite length.
  1452. var sound = self._soundById(id);
  1453. if (sound) {
  1454. duration = self._sprite[sound._sprite][1] / 1000;
  1455. }
  1456. return duration;
  1457. },
  1458. /**
  1459. * Returns the current loaded state of this Howl.
  1460. * @return {String} 'unloaded', 'loading', 'loaded'
  1461. */
  1462. state: function() {
  1463. return this._state;
  1464. },
  1465. /**
  1466. * Unload and destroy the current Howl object.
  1467. * This will immediately stop all sound instances attached to this group.
  1468. */
  1469. unload: function() {
  1470. var self = this;
  1471. // Stop playing any active sounds.
  1472. var sounds = self._sounds;
  1473. for (var i=0; i<sounds.length; i++) {
  1474. // Stop the sound if it is currently playing.
  1475. if (!sounds[i]._paused) {
  1476. self.stop(sounds[i]._id);
  1477. }
  1478. // Remove the source or disconnect.
  1479. if (!self._webAudio) {
  1480. // Set the source to 0-second silence to stop any downloading (except in IE).
  1481. self._clearSound(sounds[i]._node);
  1482. // Remove any event listeners.
  1483. sounds[i]._node.removeEventListener('error', sounds[i]._errorFn, false);
  1484. sounds[i]._node.removeEventListener(Howler._canPlayEvent, sounds[i]._loadFn, false);
  1485. sounds[i]._node.removeEventListener('ended', sounds[i]._endFn, false);
  1486. // Release the Audio object back to the pool.
  1487. Howler._releaseHtml5Audio(sounds[i]._node);
  1488. }
  1489. // Empty out all of the nodes.
  1490. delete sounds[i]._node;
  1491. // Make sure all timers are cleared out.
  1492. self._clearTimer(sounds[i]._id);
  1493. }
  1494. // Remove the references in the global Howler object.
  1495. var index = Howler._howls.indexOf(self);
  1496. if (index >= 0) {
  1497. Howler._howls.splice(index, 1);
  1498. }
  1499. // Delete this sound from the cache (if no other Howl is using it).
  1500. var remCache = true;
  1501. for (i=0; i<Howler._howls.length; i++) {
  1502. if (Howler._howls[i]._src === self._src || self._src.indexOf(Howler._howls[i]._src) >= 0) {
  1503. remCache = false;
  1504. break;
  1505. }
  1506. }
  1507. if (cache && remCache) {
  1508. delete cache[self._src];
  1509. }
  1510. // Clear global errors.
  1511. Howler.noAudio = false;
  1512. // Clear out `self`.
  1513. self._state = 'unloaded';
  1514. self._sounds = [];
  1515. self = null;
  1516. return null;
  1517. },
  1518. /**
  1519. * Listen to a custom event.
  1520. * @param {String} event Event name.
  1521. * @param {Function} fn Listener to call.
  1522. * @param {Number} id (optional) Only listen to events for this sound.
  1523. * @param {Number} once (INTERNAL) Marks event to fire only once.
  1524. * @return {Howl}
  1525. */
  1526. on: function(event, fn, id, once) {
  1527. var self = this;
  1528. var events = self['_on' + event];
  1529. if (typeof fn === 'function') {
  1530. events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn});
  1531. }
  1532. return self;
  1533. },
  1534. /**
  1535. * Remove a custom event. Call without parameters to remove all events.
  1536. * @param {String} event Event name.
  1537. * @param {Function} fn Listener to remove. Leave empty to remove all.
  1538. * @param {Number} id (optional) Only remove events for this sound.
  1539. * @return {Howl}
  1540. */
  1541. off: function(event, fn, id) {
  1542. var self = this;
  1543. var events = self['_on' + event];
  1544. var i = 0;
  1545. // Allow passing just an event and ID.
  1546. if (typeof fn === 'number') {
  1547. id = fn;
  1548. fn = null;
  1549. }
  1550. if (fn || id) {
  1551. // Loop through event store and remove the passed function.
  1552. for (i=0; i<events.length; i++) {
  1553. var isId = (id === events[i].id);
  1554. if (fn === events[i].fn && isId || !fn && isId) {
  1555. events.splice(i, 1);
  1556. break;
  1557. }
  1558. }
  1559. } else if (event) {
  1560. // Clear out all events of this type.
  1561. self['_on' + event] = [];
  1562. } else {
  1563. // Clear out all events of every type.
  1564. var keys = Object.keys(self);
  1565. for (i=0; i<keys.length; i++) {
  1566. if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) {
  1567. self[keys[i]] = [];
  1568. }
  1569. }
  1570. }
  1571. return self;
  1572. },
  1573. /**
  1574. * Listen to a custom event and remove it once fired.
  1575. * @param {String} event Event name.
  1576. * @param {Function} fn Listener to call.
  1577. * @param {Number} id (optional) Only listen to events for this sound.
  1578. * @return {Howl}
  1579. */
  1580. once: function(event, fn, id) {
  1581. var self = this;
  1582. // Setup the event listener.
  1583. self.on(event, fn, id, 1);
  1584. return self;
  1585. },
  1586. /**
  1587. * Emit all events of a specific type and pass the sound id.
  1588. * @param {String} event Event name.
  1589. * @param {Number} id Sound ID.
  1590. * @param {Number} msg Message to go with event.
  1591. * @return {Howl}
  1592. */
  1593. _emit: function(event, id, msg) {
  1594. var self = this;
  1595. var events = self['_on' + event];
  1596. // Loop through event store and fire all functions.
  1597. for (var i=events.length-1; i>=0; i--) {
  1598. // Only fire the listener if the correct ID is used.
  1599. if (!events[i].id || events[i].id === id || event === 'load') {
  1600. setTimeout(function(fn) {
  1601. fn.call(this, id, msg);
  1602. }.bind(self, events[i].fn), 0);
  1603. // If this event was setup with `once`, remove it.
  1604. if (events[i].once) {
  1605. self.off(event, events[i].fn, events[i].id);
  1606. }
  1607. }
  1608. }
  1609. // Pass the event type into load queue so that it can continue stepping.
  1610. self._loadQueue(event);
  1611. return self;
  1612. },
  1613. /**
  1614. * Queue of actions initiated before the sound has loaded.
  1615. * These will be called in sequence, with the next only firing
  1616. * after the previous has finished executing (even if async like play).
  1617. * @return {Howl}
  1618. */
  1619. _loadQueue: function(event) {
  1620. var self = this;
  1621. if (self._queue.length > 0) {
  1622. var task = self._queue[0];
  1623. // Remove this task if a matching event was passed.
  1624. if (task.event === event) {
  1625. self._queue.shift();
  1626. self._loadQueue();
  1627. }
  1628. // Run the task if no event type is passed.
  1629. if (!event) {
  1630. task.action();
  1631. }
  1632. }
  1633. return self;
  1634. },
  1635. /**
  1636. * Fired when playback ends at the end of the duration.
  1637. * @param {Sound} sound The sound object to work with.
  1638. * @return {Howl}
  1639. */
  1640. _ended: function(sound) {
  1641. var self = this;
  1642. var sprite = sound._sprite;
  1643. // If we are using IE and there was network latency we may be clipping
  1644. // audio before it completes playing. Lets check the node to make sure it
  1645. // believes it has completed, before ending the playback.
  1646. if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) {
  1647. setTimeout(self._ended.bind(self, sound), 100);
  1648. return self;
  1649. }
  1650. // Should this sound loop?
  1651. var loop = !!(sound._loop || self._sprite[sprite][2]);
  1652. // Fire the ended event.
  1653. self._emit('end', sound._id);
  1654. // Restart the playback for HTML5 Audio loop.
  1655. if (!self._webAudio && loop) {
  1656. self.stop(sound._id, true).play(sound._id);
  1657. }
  1658. // Restart this timer if on a Web Audio loop.
  1659. if (self._webAudio && loop) {
  1660. self._emit('play', sound._id);
  1661. sound._seek = sound._start || 0;
  1662. sound._rateSeek = 0;
  1663. sound._playStart = Howler.ctx.currentTime;
  1664. var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate);
  1665. self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
  1666. }
  1667. // Mark the node as paused.
  1668. if (self._webAudio && !loop) {
  1669. sound._paused = true;
  1670. sound._ended = true;
  1671. sound._seek = sound._start || 0;
  1672. sound._rateSeek = 0;
  1673. self._clearTimer(sound._id);
  1674. // Clean up the buffer source.
  1675. self._cleanBuffer(sound._node);
  1676. // Attempt to auto-suspend AudioContext if no sounds are still playing.
  1677. Howler._autoSuspend();
  1678. }
  1679. // When using a sprite, end the track.
  1680. if (!self._webAudio && !loop) {
  1681. self.stop(sound._id, true);
  1682. }
  1683. return self;
  1684. },
  1685. /**
  1686. * Clear the end timer for a sound playback.
  1687. * @param {Number} id The sound ID.
  1688. * @return {Howl}
  1689. */
  1690. _clearTimer: function(id) {
  1691. var self = this;
  1692. if (self._endTimers[id]) {
  1693. // Clear the timeout or remove the ended listener.
  1694. if (typeof self._endTimers[id] !== 'function') {
  1695. clearTimeout(self._endTimers[id]);
  1696. } else {
  1697. var sound = self._soundById(id);
  1698. if (sound && sound._node) {
  1699. sound._node.removeEventListener('ended', self._endTimers[id], false);
  1700. }
  1701. }
  1702. delete self._endTimers[id];
  1703. }
  1704. return self;
  1705. },
  1706. /**
  1707. * Return the sound identified by this ID, or return null.
  1708. * @param {Number} id Sound ID
  1709. * @return {Object} Sound object or null.
  1710. */
  1711. _soundById: function(id) {
  1712. var self = this;
  1713. // Loop through all sounds and find the one with this ID.
  1714. for (var i=0; i<self._sounds.length; i++) {
  1715. if (id === self._sounds[i]._id) {
  1716. return self._sounds[i];
  1717. }
  1718. }
  1719. return null;
  1720. },
  1721. /**
  1722. * Return an inactive sound from the pool or create a new one.
  1723. * @return {Sound} Sound playback object.
  1724. */
  1725. _inactiveSound: function() {
  1726. var self = this;
  1727. self._drain();
  1728. // Find the first inactive node to recycle.
  1729. for (var i=0; i<self._sounds.length; i++) {
  1730. if (self._sounds[i]._ended) {
  1731. return self._sounds[i].reset();
  1732. }
  1733. }
  1734. // If no inactive node was found, create a new one.
  1735. return new Sound(self);
  1736. },
  1737. /**
  1738. * Drain excess inactive sounds from the pool.
  1739. */
  1740. _drain: function() {
  1741. var self = this;
  1742. var limit = self._pool;
  1743. var cnt = 0;
  1744. var i = 0;
  1745. // If there are less sounds than the max pool size, we are done.
  1746. if (self._sounds.length < limit) {
  1747. return;
  1748. }
  1749. // Count the number of inactive sounds.
  1750. for (i=0; i<self._sounds.length; i++) {
  1751. if (self._sounds[i]._ended) {
  1752. cnt++;
  1753. }
  1754. }
  1755. // Remove excess inactive sounds, going in reverse order.
  1756. for (i=self._sounds.length - 1; i>=0; i--) {
  1757. if (cnt <= limit) {
  1758. return;
  1759. }
  1760. if (self._sounds[i]._ended) {
  1761. // Disconnect the audio source when using Web Audio.
  1762. if (self._webAudio && self._sounds[i]._node) {
  1763. self._sounds[i]._node.disconnect(0);
  1764. }
  1765. // Remove sounds until we have the pool size.
  1766. self._sounds.splice(i, 1);
  1767. cnt--;
  1768. }
  1769. }
  1770. },
  1771. /**
  1772. * Get all ID's from the sounds pool.
  1773. * @param {Number} id Only return one ID if one is passed.
  1774. * @return {Array} Array of IDs.
  1775. */
  1776. _getSoundIds: function(id) {
  1777. var self = this;
  1778. if (typeof id === 'undefined') {
  1779. var ids = [];
  1780. for (var i=0; i<self._sounds.length; i++) {
  1781. ids.push(self._sounds[i]._id);
  1782. }
  1783. return ids;
  1784. } else {
  1785. return [id];
  1786. }
  1787. },
  1788. /**
  1789. * Load the sound back into the buffer source.
  1790. * @param {Sound} sound The sound object to work with.
  1791. * @return {Howl}
  1792. */
  1793. _refreshBuffer: function(sound) {
  1794. var self = this;
  1795. // Setup the buffer source for playback.
  1796. sound._node.bufferSource = Howler.ctx.createBufferSource();
  1797. sound._node.bufferSource.buffer = cache[self._src];
  1798. // Connect to the correct node.
  1799. if (sound._panner) {
  1800. sound._node.bufferSource.connect(sound._panner);
  1801. } else {
  1802. sound._node.bufferSource.connect(sound._node);
  1803. }
  1804. // Setup looping and playback rate.
  1805. sound._node.bufferSource.loop = sound._loop;
  1806. if (sound._loop) {
  1807. sound._node.bufferSource.loopStart = sound._start || 0;
  1808. sound._node.bufferSource.loopEnd = sound._stop || 0;
  1809. }
  1810. sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime);
  1811. return self;
  1812. },
  1813. /**
  1814. * Prevent memory leaks by cleaning up the buffer source after playback.
  1815. * @param {Object} node Sound's audio node containing the buffer source.
  1816. * @return {Howl}
  1817. */
  1818. _cleanBuffer: function(node) {
  1819. var self = this;
  1820. var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0;
  1821. if (!node.bufferSource) {
  1822. return self;
  1823. }
  1824. if (Howler._scratchBuffer && node.bufferSource) {
  1825. node.bufferSource.onended = null;
  1826. node.bufferSource.disconnect(0);
  1827. if (isIOS) {
  1828. try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {}
  1829. }
  1830. }
  1831. node.bufferSource = null;
  1832. return self;
  1833. },
  1834. /**
  1835. * Set the source to a 0-second silence to stop any downloading (except in IE).
  1836. * @param {Object} node Audio node to clear.
  1837. */
  1838. _clearSound: function(node) {
  1839. var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
  1840. if (!checkIE) {
  1841. node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
  1842. }
  1843. }
  1844. };
  1845. /** Single Sound Methods **/
  1846. /***************************************************************************/
  1847. /**
  1848. * Setup the sound object, which each node attached to a Howl group is contained in.
  1849. * @param {Object} howl The Howl parent group.
  1850. */
  1851. var Sound = function(howl) {
  1852. this._parent = howl;
  1853. this.init();
  1854. };
  1855. Sound.prototype = {
  1856. /**
  1857. * Initialize a new Sound object.
  1858. * @return {Sound}
  1859. */
  1860. init: function() {
  1861. var self = this;
  1862. var parent = self._parent;
  1863. // Setup the default parameters.
  1864. self._muted = parent._muted;
  1865. self._loop = parent._loop;
  1866. self._volume = parent._volume;
  1867. self._rate = parent._rate;
  1868. self._seek = 0;
  1869. self._paused = true;
  1870. self._ended = true;
  1871. self._sprite = '__default';
  1872. // Generate a unique ID for this sound.
  1873. self._id = ++Howler._counter;
  1874. // Add itself to the parent's pool.
  1875. parent._sounds.push(self);
  1876. // Create the new node.
  1877. self.create();
  1878. return self;
  1879. },
  1880. /**
  1881. * Create and setup a new sound object, whether HTML5 Audio or Web Audio.
  1882. * @return {Sound}
  1883. */
  1884. create: function() {
  1885. var self = this;
  1886. var parent = self._parent;
  1887. var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume;
  1888. if (parent._webAudio) {
  1889. // Create the gain node for controlling volume (the source will connect to this).
  1890. self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
  1891. self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime);
  1892. self._node.paused = true;
  1893. self._node.connect(Howler.masterGain);
  1894. } else if (!Howler.noAudio) {
  1895. // Get an unlocked Audio object from the pool.
  1896. self._node = Howler._obtainHtml5Audio();
  1897. // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).
  1898. self._errorFn = self._errorListener.bind(self);
  1899. self._node.addEventListener('error', self._errorFn, false);
  1900. // Listen for 'canplaythrough' event to let us know the sound is ready.
  1901. self._loadFn = self._loadListener.bind(self);
  1902. self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false);
  1903. // Listen for the 'ended' event on the sound to account for edge-case where
  1904. // a finite sound has a duration of Infinity.
  1905. self._endFn = self._endListener.bind(self);
  1906. self._node.addEventListener('ended', self._endFn, false);
  1907. // Setup the new audio node.
  1908. self._node.src = parent._src;
  1909. self._node.preload = parent._preload === true ? 'auto' : parent._preload;
  1910. self._node.volume = volume * Howler.volume();
  1911. // Begin loading the source.
  1912. self._node.load();
  1913. }
  1914. return self;
  1915. },
  1916. /**
  1917. * Reset the parameters of this sound to the original state (for recycle).
  1918. * @return {Sound}
  1919. */
  1920. reset: function() {
  1921. var self = this;
  1922. var parent = self._parent;
  1923. // Reset all of the parameters of this sound.
  1924. self._muted = parent._muted;
  1925. self._loop = parent._loop;
  1926. self._volume = parent._volume;
  1927. self._rate = parent._rate;
  1928. self._seek = 0;
  1929. self._rateSeek = 0;
  1930. self._paused = true;
  1931. self._ended = true;
  1932. self._sprite = '__default';
  1933. // Generate a new ID so that it isn't confused with the previous sound.
  1934. self._id = ++Howler._counter;
  1935. return self;
  1936. },
  1937. /**
  1938. * HTML5 Audio error listener callback.
  1939. */
  1940. _errorListener: function() {
  1941. var self = this;
  1942. // Fire an error event and pass back the code.
  1943. self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0);
  1944. // Clear the event listener.
  1945. self._node.removeEventListener('error', self._errorFn, false);
  1946. },
  1947. /**
  1948. * HTML5 Audio canplaythrough listener callback.
  1949. */
  1950. _loadListener: function() {
  1951. var self = this;
  1952. var parent = self._parent;
  1953. // Round up the duration to account for the lower precision in HTML5 Audio.
  1954. parent._duration = Math.ceil(self._node.duration * 10) / 10;
  1955. // Setup a sprite if none is defined.
  1956. if (Object.keys(parent._sprite).length === 0) {
  1957. parent._sprite = {__default: [0, parent._duration * 1000]};
  1958. }
  1959. if (parent._state !== 'loaded') {
  1960. parent._state = 'loaded';
  1961. parent._emit('load');
  1962. parent._loadQueue();
  1963. }
  1964. // Clear the event listener.
  1965. self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
  1966. },
  1967. /**
  1968. * HTML5 Audio ended listener callback.
  1969. */
  1970. _endListener: function() {
  1971. var self = this;
  1972. var parent = self._parent;
  1973. // Only handle the `ended`` event if the duration is Infinity.
  1974. if (parent._duration === Infinity) {
  1975. // Update the parent duration to match the real audio duration.
  1976. // Round up the duration to account for the lower precision in HTML5 Audio.
  1977. parent._duration = Math.ceil(self._node.duration * 10) / 10;
  1978. // Update the sprite that corresponds to the real duration.
  1979. if (parent._sprite.__default[1] === Infinity) {
  1980. parent._sprite.__default[1] = parent._duration * 1000;
  1981. }
  1982. // Run the regular ended method.
  1983. parent._ended(self);
  1984. }
  1985. // Clear the event listener since the duration is now correct.
  1986. self._node.removeEventListener('ended', self._endFn, false);
  1987. }
  1988. };
  1989. /** Helper Methods **/
  1990. /***************************************************************************/
  1991. var cache = {};
  1992. /**
  1993. * Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
  1994. * @param {Howl} self
  1995. */
  1996. var loadBuffer = function(self) {
  1997. var url = self._src;
  1998. // Check if the buffer has already been cached and use it instead.
  1999. if (cache[url]) {
  2000. // Set the duration from the cache.
  2001. self._duration = cache[url].duration;
  2002. // Load the sound into this Howl.
  2003. loadSound(self);
  2004. return;
  2005. }
  2006. if (/^data:[^;]+;base64,/.test(url)) {
  2007. // Decode the base64 data URI without XHR, since some browsers don't support it.
  2008. var data = atob(url.split(',')[1]);
  2009. var dataView = new Uint8Array(data.length);
  2010. for (var i=0; i<data.length; ++i) {
  2011. dataView[i] = data.charCodeAt(i);
  2012. }
  2013. decodeAudioData(dataView.buffer, self);
  2014. } else {
  2015. // Load the buffer from the URL.
  2016. var xhr = new XMLHttpRequest();
  2017. xhr.open(self._xhr.method, url, true);
  2018. xhr.withCredentials = self._xhr.withCredentials;
  2019. xhr.responseType = 'arraybuffer';
  2020. // Apply any custom headers to the request.
  2021. if (self._xhr.headers) {
  2022. Object.keys(self._xhr.headers).forEach(function(key) {
  2023. xhr.setRequestHeader(key, self._xhr.headers[key]);
  2024. });
  2025. }
  2026. xhr.onload = function() {
  2027. // Make sure we get a successful response back.
  2028. var code = (xhr.status + '')[0];
  2029. if (code !== '0' && code !== '2' && code !== '3') {
  2030. self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
  2031. return;
  2032. }
  2033. decodeAudioData(xhr.response, self);
  2034. };
  2035. xhr.onerror = function() {
  2036. // If there is an error, switch to HTML5 Audio.
  2037. if (self._webAudio) {
  2038. self._html5 = true;
  2039. self._webAudio = false;
  2040. self._sounds = [];
  2041. delete cache[url];
  2042. self.load();
  2043. }
  2044. };
  2045. safeXhrSend(xhr);
  2046. }
  2047. };
  2048. /**
  2049. * Send the XHR request wrapped in a try/catch.
  2050. * @param {Object} xhr XHR to send.
  2051. */
  2052. var safeXhrSend = function(xhr) {
  2053. try {
  2054. xhr.send();
  2055. } catch (e) {
  2056. xhr.onerror();
  2057. }
  2058. };
  2059. /**
  2060. * Decode audio data from an array buffer.
  2061. * @param {ArrayBuffer} arraybuffer The audio data.
  2062. * @param {Howl} self
  2063. */
  2064. var decodeAudioData = function(arraybuffer, self) {
  2065. // Fire a load error if something broke.
  2066. var error = function() {
  2067. self._emit('loaderror', null, 'Decoding audio data failed.');
  2068. };
  2069. // Load the sound on success.
  2070. var success = function(buffer) {
  2071. if (buffer && self._sounds.length > 0) {
  2072. cache[self._src] = buffer;
  2073. loadSound(self, buffer);
  2074. } else {
  2075. error();
  2076. }
  2077. };
  2078. // Decode the buffer into an audio source.
  2079. if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
  2080. Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
  2081. } else {
  2082. Howler.ctx.decodeAudioData(arraybuffer, success, error);
  2083. }
  2084. }
  2085. /**
  2086. * Sound is now loaded, so finish setting everything up and fire the loaded event.
  2087. * @param {Howl} self
  2088. * @param {Object} buffer The decoded buffer sound source.
  2089. */
  2090. var loadSound = function(self, buffer) {
  2091. // Set the duration.
  2092. if (buffer && !self._duration) {
  2093. self._duration = buffer.duration;
  2094. }
  2095. // Setup a sprite if none is defined.
  2096. if (Object.keys(self._sprite).length === 0) {
  2097. self._sprite = {__default: [0, self._duration * 1000]};
  2098. }
  2099. // Fire the loaded event.
  2100. if (self._state !== 'loaded') {
  2101. self._state = 'loaded';
  2102. self._emit('load');
  2103. self._loadQueue();
  2104. }
  2105. };
  2106. /**
  2107. * Setup the audio context when available, or switch to HTML5 Audio mode.
  2108. */
  2109. var setupAudioContext = function() {
  2110. // If we have already detected that Web Audio isn't supported, don't run this step again.
  2111. if (!Howler.usingWebAudio) {
  2112. return;
  2113. }
  2114. // Check if we are using Web Audio and setup the AudioContext if we are.
  2115. try {
  2116. if (typeof AudioContext !== 'undefined') {
  2117. Howler.ctx = new AudioContext();
  2118. } else if (typeof webkitAudioContext !== 'undefined') {
  2119. Howler.ctx = new webkitAudioContext();
  2120. } else {
  2121. Howler.usingWebAudio = false;
  2122. }
  2123. } catch(e) {
  2124. Howler.usingWebAudio = false;
  2125. }
  2126. // If the audio context creation still failed, set using web audio to false.
  2127. if (!Howler.ctx) {
  2128. Howler.usingWebAudio = false;
  2129. }
  2130. // Check if a webview is being used on iOS8 or earlier (rather than the browser).
  2131. // If it is, disable Web Audio as it causes crashing.
  2132. var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
  2133. var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
  2134. var version = appVersion ? parseInt(appVersion[1], 10) : null;
  2135. if (iOS && version && version < 9) {
  2136. var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
  2137. if (Howler._navigator && !safari) {
  2138. Howler.usingWebAudio = false;
  2139. }
  2140. }
  2141. // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
  2142. if (Howler.usingWebAudio) {
  2143. Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
  2144. Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
  2145. Howler.masterGain.connect(Howler.ctx.destination);
  2146. }
  2147. // Re-run the setup on Howler.
  2148. Howler._setup();
  2149. };
  2150. // Add support for AMD (Asynchronous Module Definition) libraries such as require.js.
  2151. if (typeof define === 'function' && define.amd) {
  2152. define([], function() {
  2153. return {
  2154. Howler: Howler,
  2155. Howl: Howl
  2156. };
  2157. });
  2158. }
  2159. // Add support for CommonJS libraries such as browserify.
  2160. if (typeof exports !== 'undefined') {
  2161. exports.Howler = Howler;
  2162. exports.Howl = Howl;
  2163. }
  2164. // Add to global in Node.js (for testing, etc).
  2165. if (typeof global !== 'undefined') {
  2166. global.HowlerGlobal = HowlerGlobal;
  2167. global.Howler = Howler;
  2168. global.Howl = Howl;
  2169. global.Sound = Sound;
  2170. } else if (typeof window !== 'undefined') { // Define globally in case AMD is not available or unused.
  2171. window.HowlerGlobal = HowlerGlobal;
  2172. window.Howler = Howler;
  2173. window.Howl = Howl;
  2174. window.Sound = Sound;
  2175. }
  2176. })();