Web UI for ARGUS server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3242 lines
105 KiB

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