howler.min.js 105 KB

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