howler.min.js 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157
  1. /*!
  2. * howler.js v2.1.2
  3. * howlerjs.com
  4. *
  5. * (c) 2013-2019, 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. * Unload and destroy all currently loaded Howl objects.
  125. * @return {Howler}
  126. */
  127. unload: function() {
  128. var self = this || Howler;
  129. for (var i=self._howls.length-1; i>=0; i--) {
  130. self._howls[i].unload();
  131. }
  132. // Create a new AudioContext to make sure it is fully reset.
  133. if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') {
  134. self.ctx.close();
  135. self.ctx = null;
  136. setupAudioContext();
  137. }
  138. return self;
  139. },
  140. /**
  141. * Check for codec support of specific extension.
  142. * @param {String} ext Audio file extention.
  143. * @return {Boolean}
  144. */
  145. codecs: function(ext) {
  146. return (this || Howler)._codecs[ext.replace(/^x-/, '')];
  147. },
  148. /**
  149. * Setup various state values for global tracking.
  150. * @return {Howler}
  151. */
  152. _setup: function() {
  153. var self = this || Howler;
  154. // Keeps track of the suspend/resume state of the AudioContext.
  155. self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended';
  156. // Automatically begin the 30-second suspend process
  157. self._autoSuspend();
  158. // Check if audio is available.
  159. if (!self.usingWebAudio) {
  160. // No audio is available on this system if noAudio is set to true.
  161. if (typeof Audio !== 'undefined') {
  162. try {
  163. var test = new Audio();
  164. // Check if the canplaythrough event is available.
  165. if (typeof test.oncanplaythrough === 'undefined') {
  166. self._canPlayEvent = 'canplay';
  167. }
  168. } catch(e) {
  169. self.noAudio = true;
  170. }
  171. } else {
  172. self.noAudio = true;
  173. }
  174. }
  175. // Test to make sure audio isn't disabled in Internet Explorer.
  176. try {
  177. var test = new Audio();
  178. if (test.muted) {
  179. self.noAudio = true;
  180. }
  181. } catch (e) {}
  182. // Check for supported codecs.
  183. if (!self.noAudio) {
  184. self._setupCodecs();
  185. }
  186. return self;
  187. },
  188. /**
  189. * Check for browser support for various codecs and cache the results.
  190. * @return {Howler}
  191. */
  192. _setupCodecs: function() {
  193. var self = this || Howler;
  194. var audioTest = null;
  195. // Must wrap in a try/catch because IE11 in server mode throws an error.
  196. try {
  197. audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
  198. } catch (err) {
  199. return self;
  200. }
  201. if (!audioTest || typeof audioTest.canPlayType !== 'function') {
  202. return self;
  203. }
  204. var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
  205. // Opera version <33 has mixed MP3 support, so we need to check for and block it.
  206. var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/(\d+)/g);
  207. var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);
  208. self._codecs = {
  209. mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
  210. mpeg: !!mpegTest,
  211. opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
  212. ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
  213. oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
  214. wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''),
  215. aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
  216. caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
  217. m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
  218. mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
  219. weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
  220. webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
  221. dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
  222. flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
  223. };
  224. return self;
  225. },
  226. /**
  227. * Some browsers/devices will only allow audio to be played after a user interaction.
  228. * Attempt to automatically unlock audio on the first user interaction.
  229. * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
  230. * @return {Howler}
  231. */
  232. _unlockAudio: function() {
  233. var self = this || Howler;
  234. // Only run this if Web Audio is supported and it hasn't already been unlocked.
  235. if (self._audioUnlocked || !self.ctx) {
  236. return;
  237. }
  238. self._audioUnlocked = false;
  239. self.autoUnlock = false;
  240. // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views.
  241. // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000.
  242. // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate.
  243. if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) {
  244. self._mobileUnloaded = true;
  245. self.unload();
  246. }
  247. // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per:
  248. // http://stackoverflow.com/questions/24119684
  249. self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050);
  250. // Call this method on touch start to create and play a buffer,
  251. // then check if the audio actually played to determine if
  252. // audio has now been unlocked on iOS, Android, etc.
  253. var unlock = function(e) {
  254. // Create a pool of unlocked HTML5 Audio objects that can
  255. // be used for playing sounds without user interaction. HTML5
  256. // Audio objects must be individually unlocked, as opposed
  257. // to the WebAudio API which only needs a single activation.
  258. // This must occur before WebAudio setup or the source.onended
  259. // event will not fire.
  260. for (var i=0; i<self.html5PoolSize; i++) {
  261. try {
  262. var audioNode = new Audio();
  263. // Mark this Audio object as unlocked to ensure it can get returned
  264. // to the unlocked pool when released.
  265. audioNode._unlocked = true;
  266. // Add the audio node to the pool.
  267. self._releaseHtml5Audio(audioNode);
  268. } catch (e) {
  269. self.noAudio = true;
  270. }
  271. }
  272. // Loop through any assigned audio nodes and unlock them.
  273. for (var i=0; i<self._howls.length; i++) {
  274. if (!self._howls[i]._webAudio) {
  275. // Get all of the sounds in this Howl group.
  276. var ids = self._howls[i]._getSoundIds();
  277. // Loop through all sounds and unlock the audio nodes.
  278. for (var j=0; j<ids.length; j++) {
  279. var sound = self._howls[i]._soundById(ids[j]);
  280. if (sound && sound._node && !sound._node._unlocked) {
  281. sound._node._unlocked = true;
  282. sound._node.load();
  283. }
  284. }
  285. }
  286. }
  287. // Fix Android can not play in suspend state.
  288. self._autoResume();
  289. // Create an empty buffer.
  290. var source = self.ctx.createBufferSource();
  291. source.buffer = self._scratchBuffer;
  292. source.connect(self.ctx.destination);
  293. // Play the empty buffer.
  294. if (typeof source.start === 'undefined') {
  295. source.noteOn(0);
  296. } else {
  297. source.start(0);
  298. }
  299. // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
  300. if (typeof self.ctx.resume === 'function') {
  301. self.ctx.resume();
  302. }
  303. // Setup a timeout to check that we are unlocked on the next event loop.
  304. source.onended = function() {
  305. source.disconnect(0);
  306. // Update the unlocked state and prevent this check from happening again.
  307. self._audioUnlocked = true;
  308. // Remove the touch start listener.
  309. document.removeEventListener('touchstart', unlock, true);
  310. document.removeEventListener('touchend', unlock, true);
  311. document.removeEventListener('click', unlock, true);
  312. // Let all sounds know that audio has been unlocked.
  313. for (var i=0; i<self._howls.length; i++) {
  314. self._howls[i]._emit('unlock');
  315. }
  316. };
  317. };
  318. // Setup a touch start listener to attempt an unlock in.
  319. document.addEventListener('touchstart', unlock, true);
  320. document.addEventListener('touchend', unlock, true);
  321. document.addEventListener('click', unlock, true);
  322. return self;
  323. },
  324. /**
  325. * Get an unlocked HTML5 Audio object from the pool. If none are left,
  326. * return a new Audio object and throw a warning.
  327. * @return {Audio} HTML5 Audio object.
  328. */
  329. _obtainHtml5Audio: function() {
  330. var self = this || Howler;
  331. // Return the next object from the pool if one exists.
  332. if (self._html5AudioPool.length) {
  333. return self._html5AudioPool.pop();
  334. }
  335. //.Check if the audio is locked and throw a warning.
  336. var testPlay = new Audio().play();
  337. if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) {
  338. testPlay.catch(function() {
  339. console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.');
  340. });
  341. }
  342. return new Audio();
  343. },
  344. /**
  345. * Return an activated HTML5 Audio object to the pool.
  346. * @return {Howler}
  347. */
  348. _releaseHtml5Audio: function(audio) {
  349. var self = this || Howler;
  350. // Don't add audio to the pool if we don't know if it has been unlocked.
  351. if (audio._unlocked) {
  352. self._html5AudioPool.push(audio);
  353. }
  354. return self;
  355. },
  356. /**
  357. * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
  358. * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
  359. * @return {Howler}
  360. */
  361. _autoSuspend: function() {
  362. var self = this;
  363. if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) {
  364. return;
  365. }
  366. // Check if any sounds are playing.
  367. for (var i=0; i<self._howls.length; i++) {
  368. if (self._howls[i]._webAudio) {
  369. for (var j=0; j<self._howls[i]._sounds.length; j++) {
  370. if (!self._howls[i]._sounds[j]._paused) {
  371. return self;
  372. }
  373. }
  374. }
  375. }
  376. if (self._suspendTimer) {
  377. clearTimeout(self._suspendTimer);
  378. }
  379. // If no sound has played after 30 seconds, suspend the context.
  380. self._suspendTimer = setTimeout(function() {
  381. if (!self.autoSuspend) {
  382. return;
  383. }
  384. self._suspendTimer = null;
  385. self.state = 'suspending';
  386. self.ctx.suspend().then(function() {
  387. self.state = 'suspended';
  388. if (self._resumeAfterSuspend) {
  389. delete self._resumeAfterSuspend;
  390. self._autoResume();
  391. }
  392. });
  393. }, 30000);
  394. return self;
  395. },
  396. /**
  397. * Automatically resume the Web Audio AudioContext when a new sound is played.
  398. * @return {Howler}
  399. */
  400. _autoResume: function() {
  401. var self = this;
  402. if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) {
  403. return;
  404. }
  405. if (self.state === 'running' && self._suspendTimer) {
  406. clearTimeout(self._suspendTimer);
  407. self._suspendTimer = null;
  408. } else if (self.state === 'suspended') {
  409. self.ctx.resume().then(function() {
  410. self.state = 'running';
  411. // Emit to all Howls that the audio has resumed.
  412. for (var i=0; i<self._howls.length; i++) {
  413. self._howls[i]._emit('resume');
  414. }
  415. });
  416. if (self._suspendTimer) {
  417. clearTimeout(self._suspendTimer);
  418. self._suspendTimer = null;
  419. }
  420. } else if (self.state === 'suspending') {
  421. self._resumeAfterSuspend = true;
  422. }
  423. return self;
  424. }
  425. };
  426. // Setup the global audio controller.
  427. var Howler = new HowlerGlobal();
  428. /** Group Methods **/
  429. /***************************************************************************/
  430. /**
  431. * Create an audio group controller.
  432. * @param {Object} o Passed in properties for this group.
  433. */
  434. var Howl = function(o) {
  435. var self = this;
  436. // Throw an error if no source is provided.
  437. if (!o.src || o.src.length === 0) {
  438. console.error('An array of source files must be passed with any new Howl.');
  439. return;
  440. }
  441. self.init(o);
  442. };
  443. Howl.prototype = {
  444. /**
  445. * Initialize a new Howl group object.
  446. * @param {Object} o Passed in properties for this group.
  447. * @return {Howl}
  448. */
  449. init: function(o) {
  450. var self = this;
  451. // If we don't have an AudioContext created yet, run the setup.
  452. if (!Howler.ctx) {
  453. setupAudioContext();
  454. }
  455. // Setup user-defined default properties.
  456. self._autoplay = o.autoplay || false;
  457. self._format = (typeof o.format !== 'string') ? o.format : [o.format];
  458. self._html5 = o.html5 || false;
  459. self._muted = o.mute || false;
  460. self._loop = o.loop || false;
  461. self._pool = o.pool || 5;
  462. self._preload = (typeof o.preload === 'boolean') ? o.preload : true;
  463. self._rate = o.rate || 1;
  464. self._sprite = o.sprite || {};
  465. self._src = (typeof o.src !== 'string') ? o.src : [o.src];
  466. self._volume = o.volume !== undefined ? o.volume : 1;
  467. self._xhrWithCredentials = o.xhrWithCredentials || false;
  468. // Setup all other default properties.
  469. self._duration = 0;
  470. self._state = 'unloaded';
  471. self._sounds = [];
  472. self._endTimers = {};
  473. self._queue = [];
  474. self._playLock = false;
  475. // Setup event listeners.
  476. self._onend = o.onend ? [{fn: o.onend}] : [];
  477. self._onfade = o.onfade ? [{fn: o.onfade}] : [];
  478. self._onload = o.onload ? [{fn: o.onload}] : [];
  479. self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
  480. self._onplayerror = o.onplayerror ? [{fn: o.onplayerror}] : [];
  481. self._onpause = o.onpause ? [{fn: o.onpause}] : [];
  482. self._onplay = o.onplay ? [{fn: o.onplay}] : [];
  483. self._onstop = o.onstop ? [{fn: o.onstop}] : [];
  484. self._onmute = o.onmute ? [{fn: o.onmute}] : [];
  485. self._onvolume = o.onvolume ? [{fn: o.onvolume}] : [];
  486. self._onrate = o.onrate ? [{fn: o.onrate}] : [];
  487. self._onseek = o.onseek ? [{fn: o.onseek}] : [];
  488. self._onunlock = o.onunlock ? [{fn: o.onunlock}] : [];
  489. self._onresume = [];
  490. // Web Audio or HTML5 Audio?
  491. self._webAudio = Howler.usingWebAudio && !self._html5;
  492. // Automatically try to enable audio.
  493. if (typeof Howler.ctx !== 'undefined' && Howler.ctx && Howler.autoUnlock) {
  494. Howler._unlockAudio();
  495. }
  496. // Keep track of this Howl group in the global controller.
  497. Howler._howls.push(self);
  498. // If they selected autoplay, add a play event to the load queue.
  499. if (self._autoplay) {
  500. self._queue.push({
  501. event: 'play',
  502. action: function() {
  503. self.play();
  504. }
  505. });
  506. }
  507. // Load the source file unless otherwise specified.
  508. if (self._preload) {
  509. self.load();
  510. }
  511. return self;
  512. },
  513. /**
  514. * Load the audio file.
  515. * @return {Howler}
  516. */
  517. load: function() {
  518. var self = this;
  519. var url = null;
  520. // If no audio is available, quit immediately.
  521. if (Howler.noAudio) {
  522. self._emit('loaderror', null, 'No audio support.');
  523. return;
  524. }
  525. // Make sure our source is in an array.
  526. if (typeof self._src === 'string') {
  527. self._src = [self._src];
  528. }
  529. // Loop through the sources and pick the first one that is compatible.
  530. for (var i=0; i<self._src.length; i++) {
  531. var ext, str;
  532. if (self._format && self._format[i]) {
  533. // If an extension was specified, use that instead.
  534. ext = self._format[i];
  535. } else {
  536. // Make sure the source is a string.
  537. str = self._src[i];
  538. if (typeof str !== 'string') {
  539. self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.');
  540. continue;
  541. }
  542. // Extract the file extension from the URL or base64 data URI.
  543. ext = /^data:audio\/([^;,]+);/i.exec(str);
  544. if (!ext) {
  545. ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]);
  546. }
  547. if (ext) {
  548. ext = ext[1].toLowerCase();
  549. }
  550. }
  551. // Log a warning if no extension was found.
  552. if (!ext) {
  553. console.warn('No file extension was found. Consider using the "format" property or specify an extension.');
  554. }
  555. // Check if this extension is available.
  556. if (ext && Howler.codecs(ext)) {
  557. url = self._src[i];
  558. break;
  559. }
  560. }
  561. if (!url) {
  562. self._emit('loaderror', null, 'No codec support for selected audio sources.');
  563. return;
  564. }
  565. self._src = url;
  566. self._state = 'loading';
  567. // If the hosting page is HTTPS and the source isn't,
  568. // drop down to HTML5 Audio to avoid Mixed Content errors.
  569. if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') {
  570. self._html5 = true;
  571. self._webAudio = false;
  572. }
  573. // Create a new sound object and add it to the pool.
  574. new Sound(self);
  575. // Load and decode the audio data for playback.
  576. if (self._webAudio) {
  577. loadBuffer(self);
  578. }
  579. return self;
  580. },
  581. /**
  582. * Play a sound or resume previous playback.
  583. * @param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
  584. * @param {Boolean} internal Internal Use: true prevents event firing.
  585. * @return {Number} Sound ID.
  586. */
  587. play: function(sprite, internal) {
  588. var self = this;
  589. var id = null;
  590. // Determine if a sprite, sound id or nothing was passed
  591. if (typeof sprite === 'number') {
  592. id = sprite;
  593. sprite = null;
  594. } else if (typeof sprite === 'string' && self._state === 'loaded' && !self._sprite[sprite]) {
  595. // If the passed sprite doesn't exist, do nothing.
  596. return null;
  597. } else if (typeof sprite === 'undefined') {
  598. // Use the default sound sprite (plays the full audio length).
  599. sprite = '__default';
  600. // Check if there is a single paused sound that isn't ended.
  601. // If there is, play that sound. If not, continue as usual.
  602. if (!self._playLock) {
  603. var num = 0;
  604. for (var i=0; i<self._sounds.length; i++) {
  605. if (self._sounds[i]._paused && !self._sounds[i]._ended) {
  606. num++;
  607. id = self._sounds[i]._id;
  608. }
  609. }
  610. if (num === 1) {
  611. sprite = null;
  612. } else {
  613. id = null;
  614. }
  615. }
  616. }
  617. // Get the selected node, or get one from the pool.
  618. var sound = id ? self._soundById(id) : self._inactiveSound();
  619. // If the sound doesn't exist, do nothing.
  620. if (!sound) {
  621. return null;
  622. }
  623. // Select the sprite definition.
  624. if (id && !sprite) {
  625. sprite = sound._sprite || '__default';
  626. }
  627. // If the sound hasn't loaded, we must wait to get the audio's duration.
  628. // We also need to wait to make sure we don't run into race conditions with
  629. // the order of function calls.
  630. if (self._state !== 'loaded') {
  631. // Set the sprite value on this sound.
  632. sound._sprite = sprite;
  633. // Mark this sound as not ended in case another sound is played before this one loads.
  634. sound._ended = false;
  635. // Add the sound to the queue to be played on load.
  636. var soundId = sound._id;
  637. self._queue.push({
  638. event: 'play',
  639. action: function() {
  640. self.play(soundId);
  641. }
  642. });
  643. return soundId;
  644. }
  645. // Don't play the sound if an id was passed and it is already playing.
  646. if (id && !sound._paused) {
  647. // Trigger the play event, in order to keep iterating through queue.
  648. if (!internal) {
  649. self._loadQueue('play');
  650. }
  651. return sound._id;
  652. }
  653. // Make sure the AudioContext isn't suspended, and resume it if it is.
  654. if (self._webAudio) {
  655. Howler._autoResume();
  656. }
  657. // Determine how long to play for and where to start playing.
  658. var seek = Math.max(0, sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000);
  659. var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek);
  660. var timeout = (duration * 1000) / Math.abs(sound._rate);
  661. var start = self._sprite[sprite][0] / 1000;
  662. var stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
  663. var loop = !!(sound._loop || self._sprite[sprite][2]);
  664. sound._sprite = sprite;
  665. // Mark the sound as ended instantly so that this async playback
  666. // doesn't get grabbed by another call to play while this one waits to start.
  667. sound._ended = false;
  668. // Update the parameters of the sound.
  669. var setParams = function() {
  670. sound._paused = false;
  671. sound._seek = seek;
  672. sound._start = start;
  673. sound._stop = stop;
  674. sound._loop = loop;
  675. };
  676. // End the sound instantly if seek is at the end.
  677. if (seek >= stop) {
  678. self._ended(sound);
  679. return;
  680. }
  681. // Begin the actual playback.
  682. var node = sound._node;
  683. if (self._webAudio) {
  684. // Fire this when the sound is ready to play to begin Web Audio playback.
  685. var playWebAudio = function() {
  686. self._playLock = false;
  687. setParams();
  688. self._refreshBuffer(sound);
  689. // Setup the playback params.
  690. var vol = (sound._muted || self._muted) ? 0 : sound._volume;
  691. node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
  692. sound._playStart = Howler.ctx.currentTime;
  693. // Play the sound using the supported method.
  694. if (typeof node.bufferSource.start === 'undefined') {
  695. sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
  696. } else {
  697. sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
  698. }
  699. // Start a new timer if none is present.
  700. if (timeout !== Infinity) {
  701. self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
  702. }
  703. if (!internal) {
  704. setTimeout(function() {
  705. self._emit('play', sound._id);
  706. self._loadQueue();
  707. }, 0);
  708. }
  709. };
  710. if (Howler.state === 'running') {
  711. playWebAudio();
  712. } else {
  713. self._playLock = true;
  714. // Wait for the audio context to resume before playing.
  715. self.once('resume', playWebAudio);
  716. // Cancel the end timer.
  717. self._clearTimer(sound._id);
  718. }
  719. } else {
  720. // Fire this when the sound is ready to play to begin HTML5 Audio playback.
  721. var playHtml5 = function() {
  722. node.currentTime = seek;
  723. node.muted = sound._muted || self._muted || Howler._muted || node.muted;
  724. node.volume = sound._volume * Howler.volume();
  725. node.playbackRate = sound._rate;
  726. // Some browsers will throw an error if this is called without user interaction.
  727. try {
  728. var play = node.play();
  729. // Support older browsers that don't support promises, and thus don't have this issue.
  730. if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
  731. // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
  732. self._playLock = true;
  733. // Set param values immediately.
  734. setParams();
  735. // Releases the lock and executes queued actions.
  736. play
  737. .then(function() {
  738. self._playLock = false;
  739. node._unlocked = true;
  740. if (!internal) {
  741. self._emit('play', sound._id);
  742. self._loadQueue();
  743. }
  744. })
  745. .catch(function() {
  746. self._playLock = false;
  747. self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
  748. 'on mobile devices and Chrome where playback was not within a user interaction.');
  749. // Reset the ended and paused values.
  750. sound._ended = true;
  751. sound._paused = true;
  752. });
  753. } else if (!internal) {
  754. self._playLock = false;
  755. setParams();
  756. self._emit('play', sound._id);
  757. self._loadQueue();
  758. }
  759. // Setting rate before playing won't work in IE, so we set it again here.
  760. node.playbackRate = sound._rate;
  761. // If the node is still paused, then we can assume there was a playback issue.
  762. if (node.paused) {
  763. self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
  764. 'on mobile devices and Chrome where playback was not within a user interaction.');
  765. return;
  766. }
  767. // Setup the end timer on sprites or listen for the ended event.
  768. if (sprite !== '__default' || sound._loop) {
  769. self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
  770. } else {
  771. self._endTimers[sound._id] = function() {
  772. // Fire ended on this audio node.
  773. self._ended(sound);
  774. // Clear this listener.
  775. node.removeEventListener('ended', self._endTimers[sound._id], false);
  776. };
  777. node.addEventListener('ended', self._endTimers[sound._id], false);
  778. }
  779. } catch (err) {
  780. self._emit('playerror', sound._id, err);
  781. }
  782. };
  783. // If this is streaming audio, make sure the src is set and load again.
  784. if (node.src === 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA') {
  785. node.src = self._src;
  786. node.load();
  787. }
  788. // Play immediately if ready, or wait for the 'canplaythrough'e vent.
  789. var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS);
  790. if (node.readyState >= 3 || loadedNoReadyState) {
  791. playHtml5();
  792. } else {
  793. self._playLock = true;
  794. var listener = function() {
  795. // Begin playback.
  796. playHtml5();
  797. // Clear this listener.
  798. node.removeEventListener(Howler._canPlayEvent, listener, false);
  799. };
  800. node.addEventListener(Howler._canPlayEvent, listener, false);
  801. // Cancel the end timer.
  802. self._clearTimer(sound._id);
  803. }
  804. }
  805. return sound._id;
  806. },
  807. /**
  808. * Pause playback and save current position.
  809. * @param {Number} id The sound ID (empty to pause all in group).
  810. * @return {Howl}
  811. */
  812. pause: function(id) {
  813. var self = this;
  814. // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable.
  815. if (self._state !== 'loaded' || self._playLock) {
  816. self._queue.push({
  817. event: 'pause',
  818. action: function() {
  819. self.pause(id);
  820. }
  821. });
  822. return self;
  823. }
  824. // If no id is passed, get all ID's to be paused.
  825. var ids = self._getSoundIds(id);
  826. for (var i=0; i<ids.length; i++) {
  827. // Clear the end timer.
  828. self._clearTimer(ids[i]);
  829. // Get the sound.
  830. var sound = self._soundById(ids[i]);
  831. if (sound && !sound._paused) {
  832. // Reset the seek position.
  833. sound._seek = self.seek(ids[i]);
  834. sound._rateSeek = 0;
  835. sound._paused = true;
  836. // Stop currently running fades.
  837. self._stopFade(ids[i]);
  838. if (sound._node) {
  839. if (self._webAudio) {
  840. // Make sure the sound has been created.
  841. if (!sound._node.bufferSource) {
  842. continue;
  843. }
  844. if (typeof sound._node.bufferSource.stop === 'undefined') {
  845. sound._node.bufferSource.noteOff(0);
  846. } else {
  847. sound._node.bufferSource.stop(0);
  848. }
  849. // Clean up the buffer source.
  850. self._cleanBuffer(sound._node);
  851. } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
  852. sound._node.pause();
  853. }
  854. }
  855. }
  856. // Fire the pause event, unless `true` is passed as the 2nd argument.
  857. if (!arguments[1]) {
  858. self._emit('pause', sound ? sound._id : null);
  859. }
  860. }
  861. return self;
  862. },
  863. /**
  864. * Stop playback and reset to start.
  865. * @param {Number} id The sound ID (empty to stop all in group).
  866. * @param {Boolean} internal Internal Use: true prevents event firing.
  867. * @return {Howl}
  868. */
  869. stop: function(id, internal) {
  870. var self = this;
  871. // If the sound hasn't loaded, add it to the load queue to stop when capable.
  872. if (self._state !== 'loaded' || self._playLock) {
  873. self._queue.push({
  874. event: 'stop',
  875. action: function() {
  876. self.stop(id);
  877. }
  878. });
  879. return self;
  880. }
  881. // If no id is passed, get all ID's to be stopped.
  882. var ids = self._getSoundIds(id);
  883. for (var i=0; i<ids.length; i++) {
  884. // Clear the end timer.
  885. self._clearTimer(ids[i]);
  886. // Get the sound.
  887. var sound = self._soundById(ids[i]);
  888. if (sound) {
  889. // Reset the seek position.
  890. sound._seek = sound._start || 0;
  891. sound._rateSeek = 0;
  892. sound._paused = true;
  893. sound._ended = true;
  894. // Stop currently running fades.
  895. self._stopFade(ids[i]);
  896. if (sound._node) {
  897. if (self._webAudio) {
  898. // Make sure the sound's AudioBufferSourceNode has been created.
  899. if (sound._node.bufferSource) {
  900. if (typeof sound._node.bufferSource.stop === 'undefined') {
  901. sound._node.bufferSource.noteOff(0);
  902. } else {
  903. sound._node.bufferSource.stop(0);
  904. }
  905. // Clean up the buffer source.
  906. self._cleanBuffer(sound._node);
  907. }
  908. } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
  909. sound._node.currentTime = sound._start || 0;
  910. sound._node.pause();
  911. // If this is a live stream, stop download once the audio is stopped.
  912. if (sound._node.duration === Infinity) {
  913. self._clearSound(sound._node);
  914. }
  915. }
  916. }
  917. if (!internal) {
  918. self._emit('stop', sound._id);
  919. }
  920. }
  921. }
  922. return self;
  923. },
  924. /**
  925. * Mute/unmute a single sound or all sounds in this Howl group.
  926. * @param {Boolean} muted Set to true to mute and false to unmute.
  927. * @param {Number} id The sound ID to update (omit to mute/unmute all).
  928. * @return {Howl}
  929. */
  930. mute: function(muted, id) {
  931. var self = this;
  932. // If the sound hasn't loaded, add it to the load queue to mute when capable.
  933. if (self._state !== 'loaded'|| self._playLock) {
  934. self._queue.push({
  935. event: 'mute',
  936. action: function() {
  937. self.mute(muted, id);
  938. }
  939. });
  940. return self;
  941. }
  942. // If applying mute/unmute to all sounds, update the group's value.
  943. if (typeof id === 'undefined') {
  944. if (typeof muted === 'boolean') {
  945. self._muted = muted;
  946. } else {
  947. return self._muted;
  948. }
  949. }
  950. // If no id is passed, get all ID's to be muted.
  951. var ids = self._getSoundIds(id);
  952. for (var i=0; i<ids.length; i++) {
  953. // Get the sound.
  954. var sound = self._soundById(ids[i]);
  955. if (sound) {
  956. sound._muted = muted;
  957. // Cancel active fade and set the volume to the end value.
  958. if (sound._interval) {
  959. self._stopFade(sound._id);
  960. }
  961. if (self._webAudio && sound._node) {
  962. sound._node.gain.setValueAtTime(muted ? 0 : sound._volume, Howler.ctx.currentTime);
  963. } else if (sound._node) {
  964. sound._node.muted = Howler._muted ? true : muted;
  965. }
  966. self._emit('mute', sound._id);
  967. }
  968. }
  969. return self;
  970. },
  971. /**
  972. * Get/set the volume of this sound or of the Howl group. This method can optionally take 0, 1 or 2 arguments.
  973. * volume() -> Returns the group's volume value.
  974. * volume(id) -> Returns the sound id's current volume.
  975. * volume(vol) -> Sets the volume of all sounds in this Howl group.
  976. * volume(vol, id) -> Sets the volume of passed sound id.
  977. * @return {Howl/Number} Returns self or current volume.
  978. */
  979. volume: function() {
  980. var self = this;
  981. var args = arguments;
  982. var vol, id;
  983. // Determine the values based on arguments.
  984. if (args.length === 0) {
  985. // Return the value of the groups' volume.
  986. return self._volume;
  987. } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') {
  988. // First check if this is an ID, and if not, assume it is a new volume.
  989. var ids = self._getSoundIds();
  990. var index = ids.indexOf(args[0]);
  991. if (index >= 0) {
  992. id = parseInt(args[0], 10);
  993. } else {
  994. vol = parseFloat(args[0]);
  995. }
  996. } else if (args.length >= 2) {
  997. vol = parseFloat(args[0]);
  998. id = parseInt(args[1], 10);
  999. }
  1000. // Update the volume or return the current volume.
  1001. var sound;
  1002. if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
  1003. // If the sound hasn't loaded, add it to the load queue to change volume when capable.
  1004. if (self._state !== 'loaded'|| self._playLock) {
  1005. self._queue.push({
  1006. event: 'volume',
  1007. action: function() {
  1008. self.volume.apply(self, args);
  1009. }
  1010. });
  1011. return self;
  1012. }
  1013. // Set the group volume.
  1014. if (typeof id === 'undefined') {
  1015. self._volume = vol;
  1016. }
  1017. // Update one or all volumes.
  1018. id = self._getSoundIds(id);
  1019. for (var i=0; i<id.length; i++) {
  1020. // Get the sound.
  1021. sound = self._soundById(id[i]);
  1022. if (sound) {
  1023. sound._volume = vol;
  1024. // Stop currently running fades.
  1025. if (!args[2]) {
  1026. self._stopFade(id[i]);
  1027. }
  1028. if (self._webAudio && sound._node && !sound._muted) {
  1029. sound._node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
  1030. } else if (sound._node && !sound._muted) {
  1031. sound._node.volume = vol * Howler.volume();
  1032. }
  1033. self._emit('volume', sound._id);
  1034. }
  1035. }
  1036. } else {
  1037. sound = id ? self._soundById(id) : self._sounds[0];
  1038. return sound ? sound._volume : 0;
  1039. }
  1040. return self;
  1041. },
  1042. /**
  1043. * Fade a currently playing sound between two volumes (if no id is passsed, all sounds will fade).
  1044. * @param {Number} from The value to fade from (0.0 to 1.0).
  1045. * @param {Number} to The volume to fade to (0.0 to 1.0).
  1046. * @param {Number} len Time in milliseconds to fade.
  1047. * @param {Number} id The sound id (omit to fade all sounds).
  1048. * @return {Howl}
  1049. */
  1050. fade: function(from, to, len, id) {
  1051. var self = this;
  1052. // If the sound hasn't loaded, add it to the load queue to fade when capable.
  1053. if (self._state !== 'loaded' || self._playLock) {
  1054. self._queue.push({
  1055. event: 'fade',
  1056. action: function() {
  1057. self.fade(from, to, len, id);
  1058. }
  1059. });
  1060. return self;
  1061. }
  1062. // Make sure the to/from/len values are numbers.
  1063. from = parseFloat(from);
  1064. to = parseFloat(to);
  1065. len = parseFloat(len);
  1066. // Set the volume to the start position.
  1067. self.volume(from, id);
  1068. // Fade the volume of one or all sounds.
  1069. var ids = self._getSoundIds(id);
  1070. for (var i=0; i<ids.length; i++) {
  1071. // Get the sound.
  1072. var sound = self._soundById(ids[i]);
  1073. // Create a linear fade or fall back to timeouts with HTML5 Audio.
  1074. if (sound) {
  1075. // Stop the previous fade if no sprite is being used (otherwise, volume handles this).
  1076. if (!id) {
  1077. self._stopFade(ids[i]);
  1078. }
  1079. // If we are using Web Audio, let the native methods do the actual fade.
  1080. if (self._webAudio && !sound._muted) {
  1081. var currentTime = Howler.ctx.currentTime;
  1082. var end = currentTime + (len / 1000);
  1083. sound._volume = from;
  1084. sound._node.gain.setValueAtTime(from, currentTime);
  1085. sound._node.gain.linearRampToValueAtTime(to, end);
  1086. }
  1087. self._startFadeInterval(sound, from, to, len, ids[i], typeof id === 'undefined');
  1088. }
  1089. }
  1090. return self;
  1091. },
  1092. /**
  1093. * Starts the internal interval to fade a sound.
  1094. * @param {Object} sound Reference to sound to fade.
  1095. * @param {Number} from The value to fade from (0.0 to 1.0).
  1096. * @param {Number} to The volume to fade to (0.0 to 1.0).
  1097. * @param {Number} len Time in milliseconds to fade.
  1098. * @param {Number} id The sound id to fade.
  1099. * @param {Boolean} isGroup If true, set the volume on the group.
  1100. */
  1101. _startFadeInterval: function(sound, from, to, len, id, isGroup) {
  1102. var self = this;
  1103. var vol = from;
  1104. var diff = to - from;
  1105. var steps = Math.abs(diff / 0.01);
  1106. var stepLen = Math.max(4, (steps > 0) ? len / steps : len);
  1107. var lastTick = Date.now();
  1108. // Store the value being faded to.
  1109. sound._fadeTo = to;
  1110. // Update the volume value on each interval tick.
  1111. sound._interval = setInterval(function() {
  1112. // Update the volume based on the time since the last tick.
  1113. var tick = (Date.now() - lastTick) / len;
  1114. lastTick = Date.now();
  1115. vol += diff * tick;
  1116. // Make sure the volume is in the right bounds.
  1117. vol = Math.max(0, vol);
  1118. vol = Math.min(1, vol);
  1119. // Round to within 2 decimal points.
  1120. vol = Math.round(vol * 100) / 100;
  1121. // Change the volume.
  1122. if (self._webAudio) {
  1123. sound._volume = vol;
  1124. } else {
  1125. self.volume(vol, sound._id, true);
  1126. }
  1127. // Set the group's volume.
  1128. if (isGroup) {
  1129. self._volume = vol;
  1130. }
  1131. // When the fade is complete, stop it and fire event.
  1132. if ((to < from && vol <= to) || (to > from && vol >= to)) {
  1133. clearInterval(sound._interval);
  1134. sound._interval = null;
  1135. sound._fadeTo = null;
  1136. self.volume(to, sound._id);
  1137. self._emit('fade', sound._id);
  1138. }
  1139. }, stepLen);
  1140. },
  1141. /**
  1142. * Internal method that stops the currently playing fade when
  1143. * a new fade starts, volume is changed or the sound is stopped.
  1144. * @param {Number} id The sound id.
  1145. * @return {Howl}
  1146. */
  1147. _stopFade: function(id) {
  1148. var self = this;
  1149. var sound = self._soundById(id);
  1150. if (sound && sound._interval) {
  1151. if (self._webAudio) {
  1152. sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime);
  1153. }
  1154. clearInterval(sound._interval);
  1155. sound._interval = null;
  1156. self.volume(sound._fadeTo, id);
  1157. sound._fadeTo = null;
  1158. self._emit('fade', id);
  1159. }
  1160. return self;
  1161. },
  1162. /**
  1163. * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
  1164. * loop() -> Returns the group's loop value.
  1165. * loop(id) -> Returns the sound id's loop value.
  1166. * loop(loop) -> Sets the loop value for all sounds in this Howl group.
  1167. * loop(loop, id) -> Sets the loop value of passed sound id.
  1168. * @return {Howl/Boolean} Returns self or current loop value.
  1169. */
  1170. loop: function() {
  1171. var self = this;
  1172. var args = arguments;
  1173. var loop, id, sound;
  1174. // Determine the values for loop and id.
  1175. if (args.length === 0) {
  1176. // Return the grou's loop value.
  1177. return self._loop;
  1178. } else if (args.length === 1) {
  1179. if (typeof args[0] === 'boolean') {
  1180. loop = args[0];
  1181. self._loop = loop;
  1182. } else {
  1183. // Return this sound's loop value.
  1184. sound = self._soundById(parseInt(args[0], 10));
  1185. return sound ? sound._loop : false;
  1186. }
  1187. } else if (args.length === 2) {
  1188. loop = args[0];
  1189. id = parseInt(args[1], 10);
  1190. }
  1191. // If no id is passed, get all ID's to be looped.
  1192. var ids = self._getSoundIds(id);
  1193. for (var i=0; i<ids.length; i++) {
  1194. sound = self._soundById(ids[i]);
  1195. if (sound) {
  1196. sound._loop = loop;
  1197. if (self._webAudio && sound._node && sound._node.bufferSource) {
  1198. sound._node.bufferSource.loop = loop;
  1199. if (loop) {
  1200. sound._node.bufferSource.loopStart = sound._start || 0;
  1201. sound._node.bufferSource.loopEnd = sound._stop;
  1202. }
  1203. }
  1204. }
  1205. }
  1206. return self;
  1207. },
  1208. /**
  1209. * Get/set the playback rate of a sound. This method can optionally take 0, 1 or 2 arguments.
  1210. * rate() -> Returns the first sound node's current playback rate.
  1211. * rate(id) -> Returns the sound id's current playback rate.
  1212. * rate(rate) -> Sets the playback rate of all sounds in this Howl group.
  1213. * rate(rate, id) -> Sets the playback rate of passed sound id.
  1214. * @return {Howl/Number} Returns self or the current playback rate.
  1215. */
  1216. rate: function() {
  1217. var self = this;
  1218. var args = arguments;
  1219. var rate, id;
  1220. // Determine the values based on arguments.
  1221. if (args.length === 0) {
  1222. // We will simply return the current rate of the first node.
  1223. id = self._sounds[0]._id;
  1224. } else if (args.length === 1) {
  1225. // First check if this is an ID, and if not, assume it is a new rate value.
  1226. var ids = self._getSoundIds();
  1227. var index = ids.indexOf(args[0]);
  1228. if (index >= 0) {
  1229. id = parseInt(args[0], 10);
  1230. } else {
  1231. rate = parseFloat(args[0]);
  1232. }
  1233. } else if (args.length === 2) {
  1234. rate = parseFloat(args[0]);
  1235. id = parseInt(args[1], 10);
  1236. }
  1237. // Update the playback rate or return the current value.
  1238. var sound;
  1239. if (typeof rate === 'number') {
  1240. // If the sound hasn't loaded, add it to the load queue to change playback rate when capable.
  1241. if (self._state !== 'loaded' || self._playLock) {
  1242. self._queue.push({
  1243. event: 'rate',
  1244. action: function() {
  1245. self.rate.apply(self, args);
  1246. }
  1247. });
  1248. return self;
  1249. }
  1250. // Set the group rate.
  1251. if (typeof id === 'undefined') {
  1252. self._rate = rate;
  1253. }
  1254. // Update one or all volumes.
  1255. id = self._getSoundIds(id);
  1256. for (var i=0; i<id.length; i++) {
  1257. // Get the sound.
  1258. sound = self._soundById(id[i]);
  1259. if (sound) {
  1260. // Keep track of our position when the rate changed and update the playback
  1261. // start position so we can properly adjust the seek position for time elapsed.
  1262. if (self.playing(id[i])) {
  1263. sound._rateSeek = self.seek(id[i]);
  1264. sound._playStart = self._webAudio ? Howler.ctx.currentTime : sound._playStart;
  1265. }
  1266. sound._rate = rate;
  1267. // Change the playback rate.
  1268. if (self._webAudio && sound._node && sound._node.bufferSource) {
  1269. sound._node.bufferSource.playbackRate.setValueAtTime(rate, Howler.ctx.currentTime);
  1270. } else if (sound._node) {
  1271. sound._node.playbackRate = rate;
  1272. }
  1273. // Reset the timers.
  1274. var seek = self.seek(id[i]);
  1275. var duration = ((self._sprite[sound._sprite][0] + self._sprite[sound._sprite][1]) / 1000) - seek;
  1276. var timeout = (duration * 1000) / Math.abs(sound._rate);
  1277. // Start a new end timer if sound is already playing.
  1278. if (self._endTimers[id[i]] || !sound._paused) {
  1279. self._clearTimer(id[i]);
  1280. self._endTimers[id[i]] = setTimeout(self._ended.bind(self, sound), timeout);
  1281. }
  1282. self._emit('rate', sound._id);
  1283. }
  1284. }
  1285. } else {
  1286. sound = self._soundById(id);
  1287. return sound ? sound._rate : self._rate;
  1288. }
  1289. return self;
  1290. },
  1291. /**
  1292. * Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
  1293. * seek() -> Returns the first sound node's current seek position.
  1294. * seek(id) -> Returns the sound id's current seek position.
  1295. * seek(seek) -> Sets the seek position of the first sound node.
  1296. * seek(seek, id) -> Sets the seek position of passed sound id.
  1297. * @return {Howl/Number} Returns self or the current seek position.
  1298. */
  1299. seek: function() {
  1300. var self = this;
  1301. var args = arguments;
  1302. var seek, id;
  1303. // Determine the values based on arguments.
  1304. if (args.length === 0) {
  1305. // We will simply return the current position of the first node.
  1306. id = self._sounds[0]._id;
  1307. } else if (args.length === 1) {
  1308. // First check if this is an ID, and if not, assume it is a new seek position.
  1309. var ids = self._getSoundIds();
  1310. var index = ids.indexOf(args[0]);
  1311. if (index >= 0) {
  1312. id = parseInt(args[0], 10);
  1313. } else if (self._sounds.length) {
  1314. id = self._sounds[0]._id;
  1315. seek = parseFloat(args[0]);
  1316. }
  1317. } else if (args.length === 2) {
  1318. seek = parseFloat(args[0]);
  1319. id = parseInt(args[1], 10);
  1320. }
  1321. // If there is no ID, bail out.
  1322. if (typeof id === 'undefined') {
  1323. return self;
  1324. }
  1325. // If the sound hasn't loaded, add it to the load queue to seek when capable.
  1326. if (self._state !== 'loaded' || self._playLock) {
  1327. self._queue.push({
  1328. event: 'seek',
  1329. action: function() {
  1330. self.seek.apply(self, args);
  1331. }
  1332. });
  1333. return self;
  1334. }
  1335. // Get the sound.
  1336. var sound = self._soundById(id);
  1337. if (sound) {
  1338. if (typeof seek === 'number' && seek >= 0) {
  1339. // Pause the sound and update position for restarting playback.
  1340. var playing = self.playing(id);
  1341. if (playing) {
  1342. self.pause(id, true);
  1343. }
  1344. // Move the position of the track and cancel timer.
  1345. sound._seek = seek;
  1346. sound._ended = false;
  1347. self._clearTimer(id);
  1348. // Update the seek position for HTML5 Audio.
  1349. if (!self._webAudio && sound._node && !isNaN(sound._node.duration)) {
  1350. sound._node.currentTime = seek;
  1351. }
  1352. // Seek and emit when ready.
  1353. var seekAndEmit = function() {
  1354. self._emit('seek', id);
  1355. // Restart the playback if the sound was playing.
  1356. if (playing) {
  1357. self.play(id, true);
  1358. }
  1359. };
  1360. // Wait for the play lock to be unset before emitting (HTML5 Audio).
  1361. if (playing && !self._webAudio) {
  1362. var emitSeek = function() {
  1363. if (!self._playLock) {
  1364. seekAndEmit();
  1365. } else {
  1366. setTimeout(emitSeek, 0);
  1367. }
  1368. };
  1369. setTimeout(emitSeek, 0);
  1370. } else {
  1371. seekAndEmit();
  1372. }
  1373. } else {
  1374. if (self._webAudio) {
  1375. var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0;
  1376. var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0;
  1377. return sound._seek + (rateSeek + realTime * Math.abs(sound._rate));
  1378. } else {
  1379. return sound._node.currentTime;
  1380. }
  1381. }
  1382. }
  1383. return self;
  1384. },
  1385. /**
  1386. * 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.
  1387. * @param {Number} id The sound id to check. If none is passed, the whole sound group is checked.
  1388. * @return {Boolean} True if playing and false if not.
  1389. */
  1390. playing: function(id) {
  1391. var self = this;
  1392. // Check the passed sound ID (if any).
  1393. if (typeof id === 'number') {
  1394. var sound = self._soundById(id);
  1395. return sound ? !sound._paused : false;
  1396. }
  1397. // Otherwise, loop through all sounds and check if any are playing.
  1398. for (var i=0; i<self._sounds.length; i++) {
  1399. if (!self._sounds[i]._paused) {
  1400. return true;
  1401. }
  1402. }
  1403. return false;
  1404. },
  1405. /**
  1406. * Get the duration of this sound. Passing a sound id will return the sprite duration.
  1407. * @param {Number} id The sound id to check. If none is passed, return full source duration.
  1408. * @return {Number} Audio duration in seconds.
  1409. */
  1410. duration: function(id) {
  1411. var self = this;
  1412. var duration = self._duration;
  1413. // If we pass an ID, get the sound and return the sprite length.
  1414. var sound = self._soundById(id);
  1415. if (sound) {
  1416. duration = self._sprite[sound._sprite][1] / 1000;
  1417. }
  1418. return duration;
  1419. },
  1420. /**
  1421. * Returns the current loaded state of this Howl.
  1422. * @return {String} 'unloaded', 'loading', 'loaded'
  1423. */
  1424. state: function() {
  1425. return this._state;
  1426. },
  1427. /**
  1428. * Unload and destroy the current Howl object.
  1429. * This will immediately stop all sound instances attached to this group.
  1430. */
  1431. unload: function() {
  1432. var self = this;
  1433. // Stop playing any active sounds.
  1434. var sounds = self._sounds;
  1435. for (var i=0; i<sounds.length; i++) {
  1436. // Stop the sound if it is currently playing.
  1437. if (!sounds[i]._paused) {
  1438. self.stop(sounds[i]._id);
  1439. }
  1440. // Remove the source or disconnect.
  1441. if (!self._webAudio) {
  1442. // Set the source to 0-second silence to stop any downloading (except in IE).
  1443. self._clearSound(sounds[i]._node);
  1444. // Remove any event listeners.
  1445. sounds[i]._node.removeEventListener('error', sounds[i]._errorFn, false);
  1446. sounds[i]._node.removeEventListener(Howler._canPlayEvent, sounds[i]._loadFn, false);
  1447. // Release the Audio object back to the pool.
  1448. Howler._releaseHtml5Audio(sounds[i]._node);
  1449. }
  1450. // Empty out all of the nodes.
  1451. delete sounds[i]._node;
  1452. // Make sure all timers are cleared out.
  1453. self._clearTimer(sounds[i]._id);
  1454. }
  1455. // Remove the references in the global Howler object.
  1456. var index = Howler._howls.indexOf(self);
  1457. if (index >= 0) {
  1458. Howler._howls.splice(index, 1);
  1459. }
  1460. // Delete this sound from the cache (if no other Howl is using it).
  1461. var remCache = true;
  1462. for (i=0; i<Howler._howls.length; i++) {
  1463. if (Howler._howls[i]._src === self._src || self._src.indexOf(Howler._howls[i]._src) >= 0) {
  1464. remCache = false;
  1465. break;
  1466. }
  1467. }
  1468. if (cache && remCache) {
  1469. delete cache[self._src];
  1470. }
  1471. // Clear global errors.
  1472. Howler.noAudio = false;
  1473. // Clear out `self`.
  1474. self._state = 'unloaded';
  1475. self._sounds = [];
  1476. self = null;
  1477. return null;
  1478. },
  1479. /**
  1480. * Listen to a custom event.
  1481. * @param {String} event Event name.
  1482. * @param {Function} fn Listener to call.
  1483. * @param {Number} id (optional) Only listen to events for this sound.
  1484. * @param {Number} once (INTERNAL) Marks event to fire only once.
  1485. * @return {Howl}
  1486. */
  1487. on: function(event, fn, id, once) {
  1488. var self = this;
  1489. var events = self['_on' + event];
  1490. if (typeof fn === 'function') {
  1491. events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn});
  1492. }
  1493. return self;
  1494. },
  1495. /**
  1496. * Remove a custom event. Call without parameters to remove all events.
  1497. * @param {String} event Event name.
  1498. * @param {Function} fn Listener to remove. Leave empty to remove all.
  1499. * @param {Number} id (optional) Only remove events for this sound.
  1500. * @return {Howl}
  1501. */
  1502. off: function(event, fn, id) {
  1503. var self = this;
  1504. var events = self['_on' + event];
  1505. var i = 0;
  1506. // Allow passing just an event and ID.
  1507. if (typeof fn === 'number') {
  1508. id = fn;
  1509. fn = null;
  1510. }
  1511. if (fn || id) {
  1512. // Loop through event store and remove the passed function.
  1513. for (i=0; i<events.length; i++) {
  1514. var isId = (id === events[i].id);
  1515. if (fn === events[i].fn && isId || !fn && isId) {
  1516. events.splice(i, 1);
  1517. break;
  1518. }
  1519. }
  1520. } else if (event) {
  1521. // Clear out all events of this type.
  1522. self['_on' + event] = [];
  1523. } else {
  1524. // Clear out all events of every type.
  1525. var keys = Object.keys(self);
  1526. for (i=0; i<keys.length; i++) {
  1527. if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) {
  1528. self[keys[i]] = [];
  1529. }
  1530. }
  1531. }
  1532. return self;
  1533. },
  1534. /**
  1535. * Listen to a custom event and remove it once fired.
  1536. * @param {String} event Event name.
  1537. * @param {Function} fn Listener to call.
  1538. * @param {Number} id (optional) Only listen to events for this sound.
  1539. * @return {Howl}
  1540. */
  1541. once: function(event, fn, id) {
  1542. var self = this;
  1543. // Setup the event listener.
  1544. self.on(event, fn, id, 1);
  1545. return self;
  1546. },
  1547. /**
  1548. * Emit all events of a specific type and pass the sound id.
  1549. * @param {String} event Event name.
  1550. * @param {Number} id Sound ID.
  1551. * @param {Number} msg Message to go with event.
  1552. * @return {Howl}
  1553. */
  1554. _emit: function(event, id, msg) {
  1555. var self = this;
  1556. var events = self['_on' + event];
  1557. // Loop through event store and fire all functions.
  1558. for (var i=events.length-1; i>=0; i--) {
  1559. // Only fire the listener if the correct ID is used.
  1560. if (!events[i].id || events[i].id === id || event === 'load') {
  1561. setTimeout(function(fn) {
  1562. fn.call(this, id, msg);
  1563. }.bind(self, events[i].fn), 0);
  1564. // If this event was setup with `once`, remove it.
  1565. if (events[i].once) {
  1566. self.off(event, events[i].fn, events[i].id);
  1567. }
  1568. }
  1569. }
  1570. // Pass the event type into load queue so that it can continue stepping.
  1571. self._loadQueue(event);
  1572. return self;
  1573. },
  1574. /**
  1575. * Queue of actions initiated before the sound has loaded.
  1576. * These will be called in sequence, with the next only firing
  1577. * after the previous has finished executing (even if async like play).
  1578. * @return {Howl}
  1579. */
  1580. _loadQueue: function(event) {
  1581. var self = this;
  1582. if (self._queue.length > 0) {
  1583. var task = self._queue[0];
  1584. // Remove this task if a matching event was passed.
  1585. if (task.event === event) {
  1586. self._queue.shift();
  1587. self._loadQueue();
  1588. }
  1589. // Run the task if no event type is passed.
  1590. if (!event) {
  1591. task.action();
  1592. }
  1593. }
  1594. return self;
  1595. },
  1596. /**
  1597. * Fired when playback ends at the end of the duration.
  1598. * @param {Sound} sound The sound object to work with.
  1599. * @return {Howl}
  1600. */
  1601. _ended: function(sound) {
  1602. var self = this;
  1603. var sprite = sound._sprite;
  1604. // If we are using IE and there was network latency we may be clipping
  1605. // audio before it completes playing. Lets check the node to make sure it
  1606. // believes it has completed, before ending the playback.
  1607. if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) {
  1608. setTimeout(self._ended.bind(self, sound), 100);
  1609. return self;
  1610. }
  1611. // Should this sound loop?
  1612. var loop = !!(sound._loop || self._sprite[sprite][2]);
  1613. // Fire the ended event.
  1614. self._emit('end', sound._id);
  1615. // Restart the playback for HTML5 Audio loop.
  1616. if (!self._webAudio && loop) {
  1617. self.stop(sound._id, true).play(sound._id);
  1618. }
  1619. // Restart this timer if on a Web Audio loop.
  1620. if (self._webAudio && loop) {
  1621. self._emit('play', sound._id);
  1622. sound._seek = sound._start || 0;
  1623. sound._rateSeek = 0;
  1624. sound._playStart = Howler.ctx.currentTime;
  1625. var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate);
  1626. self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
  1627. }
  1628. // Mark the node as paused.
  1629. if (self._webAudio && !loop) {
  1630. sound._paused = true;
  1631. sound._ended = true;
  1632. sound._seek = sound._start || 0;
  1633. sound._rateSeek = 0;
  1634. self._clearTimer(sound._id);
  1635. // Clean up the buffer source.
  1636. self._cleanBuffer(sound._node);
  1637. // Attempt to auto-suspend AudioContext if no sounds are still playing.
  1638. Howler._autoSuspend();
  1639. }
  1640. // When using a sprite, end the track.
  1641. if (!self._webAudio && !loop) {
  1642. self.stop(sound._id, true);
  1643. }
  1644. return self;
  1645. },
  1646. /**
  1647. * Clear the end timer for a sound playback.
  1648. * @param {Number} id The sound ID.
  1649. * @return {Howl}
  1650. */
  1651. _clearTimer: function(id) {
  1652. var self = this;
  1653. if (self._endTimers[id]) {
  1654. // Clear the timeout or remove the ended listener.
  1655. if (typeof self._endTimers[id] !== 'function') {
  1656. clearTimeout(self._endTimers[id]);
  1657. } else {
  1658. var sound = self._soundById(id);
  1659. if (sound && sound._node) {
  1660. sound._node.removeEventListener('ended', self._endTimers[id], false);
  1661. }
  1662. }
  1663. delete self._endTimers[id];
  1664. }
  1665. return self;
  1666. },
  1667. /**
  1668. * Return the sound identified by this ID, or return null.
  1669. * @param {Number} id Sound ID
  1670. * @return {Object} Sound object or null.
  1671. */
  1672. _soundById: function(id) {
  1673. var self = this;
  1674. // Loop through all sounds and find the one with this ID.
  1675. for (var i=0; i<self._sounds.length; i++) {
  1676. if (id === self._sounds[i]._id) {
  1677. return self._sounds[i];
  1678. }
  1679. }
  1680. return null;
  1681. },
  1682. /**
  1683. * Return an inactive sound from the pool or create a new one.
  1684. * @return {Sound} Sound playback object.
  1685. */
  1686. _inactiveSound: function() {
  1687. var self = this;
  1688. self._drain();
  1689. // Find the first inactive node to recycle.
  1690. for (var i=0; i<self._sounds.length; i++) {
  1691. if (self._sounds[i]._ended) {
  1692. return self._sounds[i].reset();
  1693. }
  1694. }
  1695. // If no inactive node was found, create a new one.
  1696. return new Sound(self);
  1697. },
  1698. /**
  1699. * Drain excess inactive sounds from the pool.
  1700. */
  1701. _drain: function() {
  1702. var self = this;
  1703. var limit = self._pool;
  1704. var cnt = 0;
  1705. var i = 0;
  1706. // If there are less sounds than the max pool size, we are done.
  1707. if (self._sounds.length < limit) {
  1708. return;
  1709. }
  1710. // Count the number of inactive sounds.
  1711. for (i=0; i<self._sounds.length; i++) {
  1712. if (self._sounds[i]._ended) {
  1713. cnt++;
  1714. }
  1715. }
  1716. // Remove excess inactive sounds, going in reverse order.
  1717. for (i=self._sounds.length - 1; i>=0; i--) {
  1718. if (cnt <= limit) {
  1719. return;
  1720. }
  1721. if (self._sounds[i]._ended) {
  1722. // Disconnect the audio source when using Web Audio.
  1723. if (self._webAudio && self._sounds[i]._node) {
  1724. self._sounds[i]._node.disconnect(0);
  1725. }
  1726. // Remove sounds until we have the pool size.
  1727. self._sounds.splice(i, 1);
  1728. cnt--;
  1729. }
  1730. }
  1731. },
  1732. /**
  1733. * Get all ID's from the sounds pool.
  1734. * @param {Number} id Only return one ID if one is passed.
  1735. * @return {Array} Array of IDs.
  1736. */
  1737. _getSoundIds: function(id) {
  1738. var self = this;
  1739. if (typeof id === 'undefined') {
  1740. var ids = [];
  1741. for (var i=0; i<self._sounds.length; i++) {
  1742. ids.push(self._sounds[i]._id);
  1743. }
  1744. return ids;
  1745. } else {
  1746. return [id];
  1747. }
  1748. },
  1749. /**
  1750. * Load the sound back into the buffer source.
  1751. * @param {Sound} sound The sound object to work with.
  1752. * @return {Howl}
  1753. */
  1754. _refreshBuffer: function(sound) {
  1755. var self = this;
  1756. // Setup the buffer source for playback.
  1757. sound._node.bufferSource = Howler.ctx.createBufferSource();
  1758. sound._node.bufferSource.buffer = cache[self._src];
  1759. // Connect to the correct node.
  1760. if (sound._panner) {
  1761. sound._node.bufferSource.connect(sound._panner);
  1762. } else {
  1763. sound._node.bufferSource.connect(sound._node);
  1764. }
  1765. // Setup looping and playback rate.
  1766. sound._node.bufferSource.loop = sound._loop;
  1767. if (sound._loop) {
  1768. sound._node.bufferSource.loopStart = sound._start || 0;
  1769. sound._node.bufferSource.loopEnd = sound._stop || 0;
  1770. }
  1771. sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime);
  1772. return self;
  1773. },
  1774. /**
  1775. * Prevent memory leaks by cleaning up the buffer source after playback.
  1776. * @param {Object} node Sound's audio node containing the buffer source.
  1777. * @return {Howl}
  1778. */
  1779. _cleanBuffer: function(node) {
  1780. var self = this;
  1781. var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0;
  1782. if (Howler._scratchBuffer && node.bufferSource) {
  1783. node.bufferSource.onended = null;
  1784. node.bufferSource.disconnect(0);
  1785. if (isIOS) {
  1786. try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {}
  1787. }
  1788. }
  1789. node.bufferSource = null;
  1790. return self;
  1791. },
  1792. /**
  1793. * Set the source to a 0-second silence to stop any downloading (except in IE).
  1794. * @param {Object} node Audio node to clear.
  1795. */
  1796. _clearSound: function(node) {
  1797. var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
  1798. if (!checkIE) {
  1799. node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
  1800. }
  1801. }
  1802. };
  1803. /** Single Sound Methods **/
  1804. /***************************************************************************/
  1805. /**
  1806. * Setup the sound object, which each node attached to a Howl group is contained in.
  1807. * @param {Object} howl The Howl parent group.
  1808. */
  1809. var Sound = function(howl) {
  1810. this._parent = howl;
  1811. this.init();
  1812. };
  1813. Sound.prototype = {
  1814. /**
  1815. * Initialize a new Sound object.
  1816. * @return {Sound}
  1817. */
  1818. init: function() {
  1819. var self = this;
  1820. var parent = self._parent;
  1821. // Setup the default parameters.
  1822. self._muted = parent._muted;
  1823. self._loop = parent._loop;
  1824. self._volume = parent._volume;
  1825. self._rate = parent._rate;
  1826. self._seek = 0;
  1827. self._paused = true;
  1828. self._ended = true;
  1829. self._sprite = '__default';
  1830. // Generate a unique ID for this sound.
  1831. self._id = ++Howler._counter;
  1832. // Add itself to the parent's pool.
  1833. parent._sounds.push(self);
  1834. // Create the new node.
  1835. self.create();
  1836. return self;
  1837. },
  1838. /**
  1839. * Create and setup a new sound object, whether HTML5 Audio or Web Audio.
  1840. * @return {Sound}
  1841. */
  1842. create: function() {
  1843. var self = this;
  1844. var parent = self._parent;
  1845. var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume;
  1846. if (parent._webAudio) {
  1847. // Create the gain node for controlling volume (the source will connect to this).
  1848. self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
  1849. self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime);
  1850. self._node.paused = true;
  1851. self._node.connect(Howler.masterGain);
  1852. } else {
  1853. // Get an unlocked Audio object from the pool.
  1854. self._node = Howler._obtainHtml5Audio();
  1855. // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).
  1856. self._errorFn = self._errorListener.bind(self);
  1857. self._node.addEventListener('error', self._errorFn, false);
  1858. // Listen for 'canplaythrough' event to let us know the sound is ready.
  1859. self._loadFn = self._loadListener.bind(self);
  1860. self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false);
  1861. // Setup the new audio node.
  1862. self._node.src = parent._src;
  1863. self._node.preload = 'auto';
  1864. self._node.volume = volume * Howler.volume();
  1865. // Begin loading the source.
  1866. self._node.load();
  1867. }
  1868. return self;
  1869. },
  1870. /**
  1871. * Reset the parameters of this sound to the original state (for recycle).
  1872. * @return {Sound}
  1873. */
  1874. reset: function() {
  1875. var self = this;
  1876. var parent = self._parent;
  1877. // Reset all of the parameters of this sound.
  1878. self._muted = parent._muted;
  1879. self._loop = parent._loop;
  1880. self._volume = parent._volume;
  1881. self._rate = parent._rate;
  1882. self._seek = 0;
  1883. self._rateSeek = 0;
  1884. self._paused = true;
  1885. self._ended = true;
  1886. self._sprite = '__default';
  1887. // Generate a new ID so that it isn't confused with the previous sound.
  1888. self._id = ++Howler._counter;
  1889. return self;
  1890. },
  1891. /**
  1892. * HTML5 Audio error listener callback.
  1893. */
  1894. _errorListener: function() {
  1895. var self = this;
  1896. // Fire an error event and pass back the code.
  1897. self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0);
  1898. // Clear the event listener.
  1899. self._node.removeEventListener('error', self._errorFn, false);
  1900. },
  1901. /**
  1902. * HTML5 Audio canplaythrough listener callback.
  1903. */
  1904. _loadListener: function() {
  1905. var self = this;
  1906. var parent = self._parent;
  1907. // Round up the duration to account for the lower precision in HTML5 Audio.
  1908. parent._duration = Math.ceil(self._node.duration * 10) / 10;
  1909. // Setup a sprite if none is defined.
  1910. if (Object.keys(parent._sprite).length === 0) {
  1911. parent._sprite = {__default: [0, parent._duration * 1000]};
  1912. }
  1913. if (parent._state !== 'loaded') {
  1914. parent._state = 'loaded';
  1915. parent._emit('load');
  1916. parent._loadQueue();
  1917. }
  1918. // Clear the event listener.
  1919. self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
  1920. }
  1921. };
  1922. /** Helper Methods **/
  1923. /***************************************************************************/
  1924. var cache = {};
  1925. /**
  1926. * Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
  1927. * @param {Howl} self
  1928. */
  1929. var loadBuffer = function(self) {
  1930. var url = self._src;
  1931. // Check if the buffer has already been cached and use it instead.
  1932. if (cache[url]) {
  1933. // Set the duration from the cache.
  1934. self._duration = cache[url].duration;
  1935. // Load the sound into this Howl.
  1936. loadSound(self);
  1937. return;
  1938. }
  1939. if (/^data:[^;]+;base64,/.test(url)) {
  1940. // Decode the base64 data URI without XHR, since some browsers don't support it.
  1941. var data = atob(url.split(',')[1]);
  1942. var dataView = new Uint8Array(data.length);
  1943. for (var i=0; i<data.length; ++i) {
  1944. dataView[i] = data.charCodeAt(i);
  1945. }
  1946. decodeAudioData(dataView.buffer, self);
  1947. } else {
  1948. // Load the buffer from the URL.
  1949. var xhr = new XMLHttpRequest();
  1950. xhr.open('GET', url, true);
  1951. xhr.withCredentials = self._xhrWithCredentials;
  1952. xhr.responseType = 'arraybuffer';
  1953. xhr.onload = function() {
  1954. // Make sure we get a successful response back.
  1955. var code = (xhr.status + '')[0];
  1956. if (code !== '0' && code !== '2' && code !== '3') {
  1957. self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
  1958. return;
  1959. }
  1960. decodeAudioData(xhr.response, self);
  1961. };
  1962. xhr.onerror = function() {
  1963. // If there is an error, switch to HTML5 Audio.
  1964. if (self._webAudio) {
  1965. self._html5 = true;
  1966. self._webAudio = false;
  1967. self._sounds = [];
  1968. delete cache[url];
  1969. self.load();
  1970. }
  1971. };
  1972. safeXhrSend(xhr);
  1973. }
  1974. };
  1975. /**
  1976. * Send the XHR request wrapped in a try/catch.
  1977. * @param {Object} xhr XHR to send.
  1978. */
  1979. var safeXhrSend = function(xhr) {
  1980. try {
  1981. xhr.send();
  1982. } catch (e) {
  1983. xhr.onerror();
  1984. }
  1985. };
  1986. /**
  1987. * Decode audio data from an array buffer.
  1988. * @param {ArrayBuffer} arraybuffer The audio data.
  1989. * @param {Howl} self
  1990. */
  1991. var decodeAudioData = function(arraybuffer, self) {
  1992. // Fire a load error if something broke.
  1993. var error = function() {
  1994. self._emit('loaderror', null, 'Decoding audio data failed.');
  1995. };
  1996. // Load the sound on success.
  1997. var success = function(buffer) {
  1998. if (buffer && self._sounds.length > 0) {
  1999. cache[self._src] = buffer;
  2000. loadSound(self, buffer);
  2001. } else {
  2002. error();
  2003. }
  2004. };
  2005. // Decode the buffer into an audio source.
  2006. if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
  2007. Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
  2008. } else {
  2009. Howler.ctx.decodeAudioData(arraybuffer, success, error);
  2010. }
  2011. }
  2012. /**
  2013. * Sound is now loaded, so finish setting everything up and fire the loaded event.
  2014. * @param {Howl} self
  2015. * @param {Object} buffer The decoded buffer sound source.
  2016. */
  2017. var loadSound = function(self, buffer) {
  2018. // Set the duration.
  2019. if (buffer && !self._duration) {
  2020. self._duration = buffer.duration;
  2021. }
  2022. // Setup a sprite if none is defined.
  2023. if (Object.keys(self._sprite).length === 0) {
  2024. self._sprite = {__default: [0, self._duration * 1000]};
  2025. }
  2026. // Fire the loaded event.
  2027. if (self._state !== 'loaded') {
  2028. self._state = 'loaded';
  2029. self._emit('load');
  2030. self._loadQueue();
  2031. }
  2032. };
  2033. /**
  2034. * Setup the audio context when available, or switch to HTML5 Audio mode.
  2035. */
  2036. var setupAudioContext = function() {
  2037. // If we have already detected that Web Audio isn't supported, don't run this step again.
  2038. if (!Howler.usingWebAudio) {
  2039. return;
  2040. }
  2041. // Check if we are using Web Audio and setup the AudioContext if we are.
  2042. try {
  2043. if (typeof AudioContext !== 'undefined') {
  2044. Howler.ctx = new AudioContext();
  2045. } else if (typeof webkitAudioContext !== 'undefined') {
  2046. Howler.ctx = new webkitAudioContext();
  2047. } else {
  2048. Howler.usingWebAudio = false;
  2049. }
  2050. } catch(e) {
  2051. Howler.usingWebAudio = false;
  2052. }
  2053. // If the audio context creation still failed, set using web audio to false.
  2054. if (!Howler.ctx) {
  2055. Howler.usingWebAudio = false;
  2056. }
  2057. // Check if a webview is being used on iOS8 or earlier (rather than the browser).
  2058. // If it is, disable Web Audio as it causes crashing.
  2059. var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
  2060. var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
  2061. var version = appVersion ? parseInt(appVersion[1], 10) : null;
  2062. if (iOS && version && version < 9) {
  2063. var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
  2064. if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) {
  2065. Howler.usingWebAudio = false;
  2066. }
  2067. }
  2068. // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
  2069. if (Howler.usingWebAudio) {
  2070. Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
  2071. Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime);
  2072. Howler.masterGain.connect(Howler.ctx.destination);
  2073. }
  2074. // Re-run the setup on Howler.
  2075. Howler._setup();
  2076. };
  2077. // Add support for AMD (Asynchronous Module Definition) libraries such as require.js.
  2078. if (typeof define === 'function' && define.amd) {
  2079. define([], function() {
  2080. return {
  2081. Howler: Howler,
  2082. Howl: Howl
  2083. };
  2084. });
  2085. }
  2086. // Add support for CommonJS libraries such as browserify.
  2087. if (typeof exports !== 'undefined') {
  2088. exports.Howler = Howler;
  2089. exports.Howl = Howl;
  2090. }
  2091. // Define globally in case AMD is not available or unused.
  2092. if (typeof window !== 'undefined') {
  2093. window.HowlerGlobal = HowlerGlobal;
  2094. window.Howler = Howler;
  2095. window.Howl = Howl;
  2096. window.Sound = Sound;
  2097. } else if (typeof global !== 'undefined') { // Add to global in Node.js (for testing, etc).
  2098. global.HowlerGlobal = HowlerGlobal;
  2099. global.Howler = Howler;
  2100. global.Howl = Howl;
  2101. global.Sound = Sound;
  2102. }
  2103. })();
  2104. /*!
  2105. * Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported.
  2106. *
  2107. * howler.js v2.1.2
  2108. * howlerjs.com
  2109. *
  2110. * (c) 2013-2019, James Simpson of GoldFire Studios
  2111. * goldfirestudios.com
  2112. *
  2113. * MIT License
  2114. */
  2115. (function() {
  2116. 'use strict';
  2117. // Setup default properties.
  2118. HowlerGlobal.prototype._pos = [0, 0, 0];
  2119. HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0];
  2120. /** Global Methods **/
  2121. /***************************************************************************/
  2122. /**
  2123. * Helper method to update the stereo panning position of all current Howls.
  2124. * Future Howls will not use this value unless explicitly set.
  2125. * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
  2126. * @return {Howler/Number} Self or current stereo panning value.
  2127. */
  2128. HowlerGlobal.prototype.stereo = function(pan) {
  2129. var self = this;
  2130. // Stop right here if not using Web Audio.
  2131. if (!self.ctx || !self.ctx.listener) {
  2132. return self;
  2133. }
  2134. // Loop through all Howls and update their stereo panning.
  2135. for (var i=self._howls.length-1; i>=0; i--) {
  2136. self._howls[i].stereo(pan);
  2137. }
  2138. return self;
  2139. };
  2140. /**
  2141. * Get/set the position of the listener in 3D cartesian space. Sounds using
  2142. * 3D position will be relative to the listener's position.
  2143. * @param {Number} x The x-position of the listener.
  2144. * @param {Number} y The y-position of the listener.
  2145. * @param {Number} z The z-position of the listener.
  2146. * @return {Howler/Array} Self or current listener position.
  2147. */
  2148. HowlerGlobal.prototype.pos = function(x, y, z) {
  2149. var self = this;
  2150. // Stop right here if not using Web Audio.
  2151. if (!self.ctx || !self.ctx.listener) {
  2152. return self;
  2153. }
  2154. // Set the defaults for optional 'y' & 'z'.
  2155. y = (typeof y !== 'number') ? self._pos[1] : y;
  2156. z = (typeof z !== 'number') ? self._pos[2] : z;
  2157. if (typeof x === 'number') {
  2158. self._pos = [x, y, z];
  2159. if (typeof self.ctx.listener.positionX !== 'undefined') {
  2160. self.ctx.listener.positionX.setTargetAtTime(self._pos[0], Howler.ctx.currentTime, 0.1);
  2161. self.ctx.listener.positionY.setTargetAtTime(self._pos[1], Howler.ctx.currentTime, 0.1);
  2162. self.ctx.listener.positionZ.setTargetAtTime(self._pos[2], Howler.ctx.currentTime, 0.1);
  2163. } else {
  2164. self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]);
  2165. }
  2166. } else {
  2167. return self._pos;
  2168. }
  2169. return self;
  2170. };
  2171. /**
  2172. * Get/set the direction the listener is pointing in the 3D cartesian space.
  2173. * A front and up vector must be provided. The front is the direction the
  2174. * face of the listener is pointing, and up is the direction the top of the
  2175. * listener is pointing. Thus, these values are expected to be at right angles
  2176. * from each other.
  2177. * @param {Number} x The x-orientation of the listener.
  2178. * @param {Number} y The y-orientation of the listener.
  2179. * @param {Number} z The z-orientation of the listener.
  2180. * @param {Number} xUp The x-orientation of the top of the listener.
  2181. * @param {Number} yUp The y-orientation of the top of the listener.
  2182. * @param {Number} zUp The z-orientation of the top of the listener.
  2183. * @return {Howler/Array} Returns self or the current orientation vectors.
  2184. */
  2185. HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) {
  2186. var self = this;
  2187. // Stop right here if not using Web Audio.
  2188. if (!self.ctx || !self.ctx.listener) {
  2189. return self;
  2190. }
  2191. // Set the defaults for optional 'y' & 'z'.
  2192. var or = self._orientation;
  2193. y = (typeof y !== 'number') ? or[1] : y;
  2194. z = (typeof z !== 'number') ? or[2] : z;
  2195. xUp = (typeof xUp !== 'number') ? or[3] : xUp;
  2196. yUp = (typeof yUp !== 'number') ? or[4] : yUp;
  2197. zUp = (typeof zUp !== 'number') ? or[5] : zUp;
  2198. if (typeof x === 'number') {
  2199. self._orientation = [x, y, z, xUp, yUp, zUp];
  2200. if (typeof self.ctx.listener.forwardX !== 'undefined') {
  2201. self.ctx.listener.forwardX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
  2202. self.ctx.listener.forwardY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
  2203. self.ctx.listener.forwardZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
  2204. self.ctx.listener.upX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
  2205. self.ctx.listener.upY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
  2206. self.ctx.listener.upZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
  2207. } else {
  2208. self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp);
  2209. }
  2210. } else {
  2211. return or;
  2212. }
  2213. return self;
  2214. };
  2215. /** Group Methods **/
  2216. /***************************************************************************/
  2217. /**
  2218. * Add new properties to the core init.
  2219. * @param {Function} _super Core init method.
  2220. * @return {Howl}
  2221. */
  2222. Howl.prototype.init = (function(_super) {
  2223. return function(o) {
  2224. var self = this;
  2225. // Setup user-defined default properties.
  2226. self._orientation = o.orientation || [1, 0, 0];
  2227. self._stereo = o.stereo || null;
  2228. self._pos = o.pos || null;
  2229. self._pannerAttr = {
  2230. coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360,
  2231. coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360,
  2232. coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0,
  2233. distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse',
  2234. maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000,
  2235. panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF',
  2236. refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1,
  2237. rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1
  2238. };
  2239. // Setup event listeners.
  2240. self._onstereo = o.onstereo ? [{fn: o.onstereo}] : [];
  2241. self._onpos = o.onpos ? [{fn: o.onpos}] : [];
  2242. self._onorientation = o.onorientation ? [{fn: o.onorientation}] : [];
  2243. // Complete initilization with howler.js core's init function.
  2244. return _super.call(this, o);
  2245. };
  2246. })(Howl.prototype.init);
  2247. /**
  2248. * Get/set the stereo panning of the audio source for this sound or all in the group.
  2249. * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
  2250. * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
  2251. * @return {Howl/Number} Returns self or the current stereo panning value.
  2252. */
  2253. Howl.prototype.stereo = function(pan, id) {
  2254. var self = this;
  2255. // Stop right here if not using Web Audio.
  2256. if (!self._webAudio) {
  2257. return self;
  2258. }
  2259. // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable.
  2260. if (self._state !== 'loaded') {
  2261. self._queue.push({
  2262. event: 'stereo',
  2263. action: function() {
  2264. self.stereo(pan, id);
  2265. }
  2266. });
  2267. return self;
  2268. }
  2269. // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist.
  2270. var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo';
  2271. // Setup the group's stereo panning if no ID is passed.
  2272. if (typeof id === 'undefined') {
  2273. // Return the group's stereo panning if no parameters are passed.
  2274. if (typeof pan === 'number') {
  2275. self._stereo = pan;
  2276. self._pos = [pan, 0, 0];
  2277. } else {
  2278. return self._stereo;
  2279. }
  2280. }
  2281. // Change the streo panning of one or all sounds in group.
  2282. var ids = self._getSoundIds(id);
  2283. for (var i=0; i<ids.length; i++) {
  2284. // Get the sound.
  2285. var sound = self._soundById(ids[i]);
  2286. if (sound) {
  2287. if (typeof pan === 'number') {
  2288. sound._stereo = pan;
  2289. sound._pos = [pan, 0, 0];
  2290. if (sound._node) {
  2291. // If we are falling back, make sure the panningModel is equalpower.
  2292. sound._pannerAttr.panningModel = 'equalpower';
  2293. // Check if there is a panner setup and create a new one if not.
  2294. if (!sound._panner || !sound._panner.pan) {
  2295. setupPanner(sound, pannerType);
  2296. }
  2297. if (pannerType === 'spatial') {
  2298. if (typeof sound._panner.positionX !== 'undefined') {
  2299. sound._panner.positionX.setValueAtTime(pan, Howler.ctx.currentTime);
  2300. sound._panner.positionY.setValueAtTime(0, Howler.ctx.currentTime);
  2301. sound._panner.positionZ.setValueAtTime(0, Howler.ctx.currentTime);
  2302. } else {
  2303. sound._panner.setPosition(pan, 0, 0);
  2304. }
  2305. } else {
  2306. sound._panner.pan.setValueAtTime(pan, Howler.ctx.currentTime);
  2307. }
  2308. }
  2309. self._emit('stereo', sound._id);
  2310. } else {
  2311. return sound._stereo;
  2312. }
  2313. }
  2314. }
  2315. return self;
  2316. };
  2317. /**
  2318. * Get/set the 3D spatial position of the audio source for this sound or group relative to the global listener.
  2319. * @param {Number} x The x-position of the audio source.
  2320. * @param {Number} y The y-position of the audio source.
  2321. * @param {Number} z The z-position of the audio source.
  2322. * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
  2323. * @return {Howl/Array} Returns self or the current 3D spatial position: [x, y, z].
  2324. */
  2325. Howl.prototype.pos = function(x, y, z, id) {
  2326. var self = this;
  2327. // Stop right here if not using Web Audio.
  2328. if (!self._webAudio) {
  2329. return self;
  2330. }
  2331. // If the sound hasn't loaded, add it to the load queue to change position when capable.
  2332. if (self._state !== 'loaded') {
  2333. self._queue.push({
  2334. event: 'pos',
  2335. action: function() {
  2336. self.pos(x, y, z, id);
  2337. }
  2338. });
  2339. return self;
  2340. }
  2341. // Set the defaults for optional 'y' & 'z'.
  2342. y = (typeof y !== 'number') ? 0 : y;
  2343. z = (typeof z !== 'number') ? -0.5 : z;
  2344. // Setup the group's spatial position if no ID is passed.
  2345. if (typeof id === 'undefined') {
  2346. // Return the group's spatial position if no parameters are passed.
  2347. if (typeof x === 'number') {
  2348. self._pos = [x, y, z];
  2349. } else {
  2350. return self._pos;
  2351. }
  2352. }
  2353. // Change the spatial position of one or all sounds in group.
  2354. var ids = self._getSoundIds(id);
  2355. for (var i=0; i<ids.length; i++) {
  2356. // Get the sound.
  2357. var sound = self._soundById(ids[i]);
  2358. if (sound) {
  2359. if (typeof x === 'number') {
  2360. sound._pos = [x, y, z];
  2361. if (sound._node) {
  2362. // Check if there is a panner setup and create a new one if not.
  2363. if (!sound._panner || sound._panner.pan) {
  2364. setupPanner(sound, 'spatial');
  2365. }
  2366. if (typeof sound._panner.positionX !== 'undefined') {
  2367. sound._panner.positionX.setValueAtTime(x, Howler.ctx.currentTime);
  2368. sound._panner.positionY.setValueAtTime(y, Howler.ctx.currentTime);
  2369. sound._panner.positionZ.setValueAtTime(z, Howler.ctx.currentTime);
  2370. } else {
  2371. sound._panner.setPosition(x, y, z);
  2372. }
  2373. }
  2374. self._emit('pos', sound._id);
  2375. } else {
  2376. return sound._pos;
  2377. }
  2378. }
  2379. }
  2380. return self;
  2381. };
  2382. /**
  2383. * Get/set the direction the audio source is pointing in the 3D cartesian coordinate
  2384. * space. Depending on how direction the sound is, based on the `cone` attributes,
  2385. * a sound pointing away from the listener can be quiet or silent.
  2386. * @param {Number} x The x-orientation of the source.
  2387. * @param {Number} y The y-orientation of the source.
  2388. * @param {Number} z The z-orientation of the source.
  2389. * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
  2390. * @return {Howl/Array} Returns self or the current 3D spatial orientation: [x, y, z].
  2391. */
  2392. Howl.prototype.orientation = function(x, y, z, id) {
  2393. var self = this;
  2394. // Stop right here if not using Web Audio.
  2395. if (!self._webAudio) {
  2396. return self;
  2397. }
  2398. // If the sound hasn't loaded, add it to the load queue to change orientation when capable.
  2399. if (self._state !== 'loaded') {
  2400. self._queue.push({
  2401. event: 'orientation',
  2402. action: function() {
  2403. self.orientation(x, y, z, id);
  2404. }
  2405. });
  2406. return self;
  2407. }
  2408. // Set the defaults for optional 'y' & 'z'.
  2409. y = (typeof y !== 'number') ? self._orientation[1] : y;
  2410. z = (typeof z !== 'number') ? self._orientation[2] : z;
  2411. // Setup the group's spatial orientation if no ID is passed.
  2412. if (typeof id === 'undefined') {
  2413. // Return the group's spatial orientation if no parameters are passed.
  2414. if (typeof x === 'number') {
  2415. self._orientation = [x, y, z];
  2416. } else {
  2417. return self._orientation;
  2418. }
  2419. }
  2420. // Change the spatial orientation of one or all sounds in group.
  2421. var ids = self._getSoundIds(id);
  2422. for (var i=0; i<ids.length; i++) {
  2423. // Get the sound.
  2424. var sound = self._soundById(ids[i]);
  2425. if (sound) {
  2426. if (typeof x === 'number') {
  2427. sound._orientation = [x, y, z];
  2428. if (sound._node) {
  2429. // Check if there is a panner setup and create a new one if not.
  2430. if (!sound._panner) {
  2431. // Make sure we have a position to setup the node with.
  2432. if (!sound._pos) {
  2433. sound._pos = self._pos || [0, 0, -0.5];
  2434. }
  2435. setupPanner(sound, 'spatial');
  2436. }
  2437. if (typeof sound._panner.orientationX !== 'undefined') {
  2438. sound._panner.orientationX.setValueAtTime(x, Howler.ctx.currentTime);
  2439. sound._panner.orientationY.setValueAtTime(y, Howler.ctx.currentTime);
  2440. sound._panner.orientationZ.setValueAtTime(z, Howler.ctx.currentTime);
  2441. } else {
  2442. sound._panner.setOrientation(x, y, z);
  2443. }
  2444. }
  2445. self._emit('orientation', sound._id);
  2446. } else {
  2447. return sound._orientation;
  2448. }
  2449. }
  2450. }
  2451. return self;
  2452. };
  2453. /**
  2454. * Get/set the panner node's attributes for a sound or group of sounds.
  2455. * This method can optionall take 0, 1 or 2 arguments.
  2456. * pannerAttr() -> Returns the group's values.
  2457. * pannerAttr(id) -> Returns the sound id's values.
  2458. * pannerAttr(o) -> Set's the values of all sounds in this Howl group.
  2459. * pannerAttr(o, id) -> Set's the values of passed sound id.
  2460. *
  2461. * Attributes:
  2462. * coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
  2463. * inside of which there will be no volume reduction.
  2464. * coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
  2465. * outside of which the volume will be reduced to a constant value of `coneOuterGain`.
  2466. * coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the
  2467. * `coneOuterAngle`. It is a linear value in the range `[0, 1]`.
  2468. * distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from
  2469. * listener. Can be `linear`, `inverse` or `exponential.
  2470. * maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume
  2471. * will not be reduced any further.
  2472. * refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener.
  2473. * This is simply a variable of the distance model and has a different effect depending on which model
  2474. * is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance.
  2475. * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a
  2476. * variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]`
  2477. * with `inverse` and `exponential`.
  2478. * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio.
  2479. * Can be `HRTF` or `equalpower`.
  2480. *
  2481. * @return {Howl/Object} Returns self or current panner attributes.
  2482. */
  2483. Howl.prototype.pannerAttr = function() {
  2484. var self = this;
  2485. var args = arguments;
  2486. var o, id, sound;
  2487. // Stop right here if not using Web Audio.
  2488. if (!self._webAudio) {
  2489. return self;
  2490. }
  2491. // Determine the values based on arguments.
  2492. if (args.length === 0) {
  2493. // Return the group's panner attribute values.
  2494. return self._pannerAttr;
  2495. } else if (args.length === 1) {
  2496. if (typeof args[0] === 'object') {
  2497. o = args[0];
  2498. // Set the grou's panner attribute values.
  2499. if (typeof id === 'undefined') {
  2500. if (!o.pannerAttr) {
  2501. o.pannerAttr = {
  2502. coneInnerAngle: o.coneInnerAngle,
  2503. coneOuterAngle: o.coneOuterAngle,
  2504. coneOuterGain: o.coneOuterGain,
  2505. distanceModel: o.distanceModel,
  2506. maxDistance: o.maxDistance,
  2507. refDistance: o.refDistance,
  2508. rolloffFactor: o.rolloffFactor,
  2509. panningModel: o.panningModel
  2510. };
  2511. }
  2512. self._pannerAttr = {
  2513. coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle,
  2514. coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle,
  2515. coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain,
  2516. distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel,
  2517. maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance,
  2518. refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance,
  2519. rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor,
  2520. panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel
  2521. };
  2522. }
  2523. } else {
  2524. // Return this sound's panner attribute values.
  2525. sound = self._soundById(parseInt(args[0], 10));
  2526. return sound ? sound._pannerAttr : self._pannerAttr;
  2527. }
  2528. } else if (args.length === 2) {
  2529. o = args[0];
  2530. id = parseInt(args[1], 10);
  2531. }
  2532. // Update the values of the specified sounds.
  2533. var ids = self._getSoundIds(id);
  2534. for (var i=0; i<ids.length; i++) {
  2535. sound = self._soundById(ids[i]);
  2536. if (sound) {
  2537. // Merge the new values into the sound.
  2538. var pa = sound._pannerAttr;
  2539. pa = {
  2540. coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : pa.coneInnerAngle,
  2541. coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : pa.coneOuterAngle,
  2542. coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : pa.coneOuterGain,
  2543. distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : pa.distanceModel,
  2544. maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : pa.maxDistance,
  2545. refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : pa.refDistance,
  2546. rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : pa.rolloffFactor,
  2547. panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : pa.panningModel
  2548. };
  2549. // Update the panner values or create a new panner if none exists.
  2550. var panner = sound._panner;
  2551. if (panner) {
  2552. panner.coneInnerAngle = pa.coneInnerAngle;
  2553. panner.coneOuterAngle = pa.coneOuterAngle;
  2554. panner.coneOuterGain = pa.coneOuterGain;
  2555. panner.distanceModel = pa.distanceModel;
  2556. panner.maxDistance = pa.maxDistance;
  2557. panner.refDistance = pa.refDistance;
  2558. panner.rolloffFactor = pa.rolloffFactor;
  2559. panner.panningModel = pa.panningModel;
  2560. } else {
  2561. // Make sure we have a position to setup the node with.
  2562. if (!sound._pos) {
  2563. sound._pos = self._pos || [0, 0, -0.5];
  2564. }
  2565. // Create a new panner node.
  2566. setupPanner(sound, 'spatial');
  2567. }
  2568. }
  2569. }
  2570. return self;
  2571. };
  2572. /** Single Sound Methods **/
  2573. /***************************************************************************/
  2574. /**
  2575. * Add new properties to the core Sound init.
  2576. * @param {Function} _super Core Sound init method.
  2577. * @return {Sound}
  2578. */
  2579. Sound.prototype.init = (function(_super) {
  2580. return function() {
  2581. var self = this;
  2582. var parent = self._parent;
  2583. // Setup user-defined default properties.
  2584. self._orientation = parent._orientation;
  2585. self._stereo = parent._stereo;
  2586. self._pos = parent._pos;
  2587. self._pannerAttr = parent._pannerAttr;
  2588. // Complete initilization with howler.js core Sound's init function.
  2589. _super.call(this);
  2590. // If a stereo or position was specified, set it up.
  2591. if (self._stereo) {
  2592. parent.stereo(self._stereo);
  2593. } else if (self._pos) {
  2594. parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
  2595. }
  2596. };
  2597. })(Sound.prototype.init);
  2598. /**
  2599. * Override the Sound.reset method to clean up properties from the spatial plugin.
  2600. * @param {Function} _super Sound reset method.
  2601. * @return {Sound}
  2602. */
  2603. Sound.prototype.reset = (function(_super) {
  2604. return function() {
  2605. var self = this;
  2606. var parent = self._parent;
  2607. // Reset all spatial plugin properties on this sound.
  2608. self._orientation = parent._orientation;
  2609. self._stereo = parent._stereo;
  2610. self._pos = parent._pos;
  2611. self._pannerAttr = parent._pannerAttr;
  2612. // If a stereo or position was specified, set it up.
  2613. if (self._stereo) {
  2614. parent.stereo(self._stereo);
  2615. } else if (self._pos) {
  2616. parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
  2617. } else if (self._panner) {
  2618. // Disconnect the panner.
  2619. self._panner.disconnect(0);
  2620. self._panner = undefined;
  2621. parent._refreshBuffer(self);
  2622. }
  2623. // Complete resetting of the sound.
  2624. return _super.call(this);
  2625. };
  2626. })(Sound.prototype.reset);
  2627. /** Helper Methods **/
  2628. /***************************************************************************/
  2629. /**
  2630. * Create a new panner node and save it on the sound.
  2631. * @param {Sound} sound Specific sound to setup panning on.
  2632. * @param {String} type Type of panner to create: 'stereo' or 'spatial'.
  2633. */
  2634. var setupPanner = function(sound, type) {
  2635. type = type || 'spatial';
  2636. // Create the new panner node.
  2637. if (type === 'spatial') {
  2638. sound._panner = Howler.ctx.createPanner();
  2639. sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
  2640. sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
  2641. sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
  2642. sound._panner.distanceModel = sound._pannerAttr.distanceModel;
  2643. sound._panner.maxDistance = sound._pannerAttr.maxDistance;
  2644. sound._panner.refDistance = sound._pannerAttr.refDistance;
  2645. sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
  2646. sound._panner.panningModel = sound._pannerAttr.panningModel;
  2647. if (typeof sound._panner.positionX !== 'undefined') {
  2648. sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
  2649. sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
  2650. sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
  2651. } else {
  2652. sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
  2653. }
  2654. if (typeof sound._panner.orientationX !== 'undefined') {
  2655. sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
  2656. sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
  2657. sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
  2658. } else {
  2659. sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
  2660. }
  2661. } else {
  2662. sound._panner = Howler.ctx.createStereoPanner();
  2663. sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
  2664. }
  2665. sound._panner.connect(sound._node);
  2666. // Update the connections.
  2667. if (!sound._paused) {
  2668. sound._parent.pause(sound._id, true).play(sound._id, true);
  2669. }
  2670. };
  2671. })();