howler.min.js 105 KB

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