howler.js 105 KB

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