howler.min.js 105 KB

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