Brak opisu

howler.js 86KB

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