Ver Fonte

创建web端录制音频仓储

loki.wu há 2 anos atrás
commit
9f5d7cb746

+ 4 - 0
CHANGELOG.md

@@ -0,0 +1,4 @@
+## 9.2.13
+
+- Please [look to this](https://dooboolab.github.io/flutter_sound/book/CHANGELOG.html)
+

+ 153 - 0
LICENSE

@@ -0,0 +1,153 @@
+# Mozilla Public License
+
+Version 2.0
+
+1. Definitions
+1.1. “Contributor”
+means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+means
+
+that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
+
+that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.
+
+1.6. “Executable Form”
+means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.
+
+1.8. “License”
+means this document.
+
+1.9. “Licensable”
+means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.
+
+1.10. “Modifications”
+means any of the following:
+
+any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
+
+any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
+
+2. License Grants and Conditions
+2.1. Grants
+Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
+
+under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
+
+under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.
+
+2.2. Effective Date
+The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor:
+
+for any code that a Contributor has removed from Covered Software; or
+
+for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
+
+under Patent Claims infringed by Covered Software in the absence of its Contributions.
+
+This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3).
+
+2.5. Representation
+Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.
+
+3. Responsibilities
+3.1. Distribution of Source Form
+All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+If You distribute Covered Software in Executable Form then:
+
+such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
+
+You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).
+
+3.4. Notices
+You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
+
+5. Termination
+5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.
+
+6. Disclaimer of Warranty
+Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
+
+7. Limitation of Liability
+Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+10.1. New Versions
+Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
+
+10.2. Effect of New Versions
+You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.
+
+10.3. Modified Versions
+If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.

+ 3 - 0
README.md

@@ -0,0 +1,3 @@
+# Flutter Sound_web
+
+This is the Flutter Web implementation of Flutter Sound

Diff do ficheiro suprimidas por serem muito extensas
+ 1 - 0
howler/howler.core.min.js


+ 3193 - 0
howler/howler.js

@@ -0,0 +1,3193 @@
+/*!
+ *  howler.js v2.2.0
+ *  howlerjs.com
+ *
+ *  (c) 2013-2020, James Simpson of GoldFire Studios
+ *  goldfirestudios.com
+ *
+ *  MIT License
+ */
+
+(function() {
+
+  'use strict';
+
+  /** Global Methods **/
+  /***************************************************************************/
+
+  /**
+   * Create the global controller. All contained methods and properties apply
+   * to all sounds that are currently playing or will be in the future.
+   */
+  var HowlerGlobal = function() {
+    this.init();
+  };
+  HowlerGlobal.prototype = {
+    /**
+     * Initialize the global Howler object.
+     * @return {Howler}
+     */
+    init: function() {
+      var self = this || Howler;
+
+      // Create a global ID counter.
+      self._counter = 1000;
+
+      // Pool of unlocked HTML5 Audio objects.
+      self._html5AudioPool = [];
+      self.html5PoolSize = 10;
+
+      // Internal properties.
+      self._codecs = {};
+      self._howls = [];
+      self._muted = false;
+      self._volume = 1;
+      self._canPlayEvent = 'canplaythrough';
+      self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null;
+
+      // Public properties.
+      self.masterGain = null;
+      self.noAudio = false;
+      self.usingWebAudio = true;
+      self.autoSuspend = true;
+      self.ctx = null;
+
+      // Set to false to disable the auto audio unlocker.
+      self.autoUnlock = true;
+
+      // Setup the various state values for global tracking.
+      self._setup();
+
+      return self;
+    },
+
+    /**
+     * Get/set the global volume for all sounds.
+     * @param  {Float} vol Volume from 0.0 to 1.0.
+     * @return {Howler/Float}     Returns self or current volume.
+     */
+    volume: function(vol) {
+      var self = this || Howler;
+      vol = parseFloat(vol);
+
+      // If we don't have an AudioContext created yet, run the setup.
+      if (!self.ctx) {
+        setupAudioContext();
+      }
+
+      if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
+        self._volume = vol;
+
+        // Don't update any of the nodes if we are muted.
+        if (self._muted) {
+          return self;
+        }
+
+        // When using Web Audio, we just need to adjust the master gain.
+        if (self.usingWebAudio) {
+          self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime);
+        }
+
+        // Loop through and change volume for all HTML5 audio nodes.
+        for (var i=0; i<self._howls.length; i++) {
+          if (!self._howls[i]._webAudio) {
+            // Get all of the sounds in this Howl group.
+            var ids = self._howls[i]._getSoundIds();
+
+            // Loop through all sounds and change the volumes.
+            for (var j=0; j<ids.length; j++) {
+              var sound = self._howls[i]._soundById(ids[j]);
+
+              if (sound && sound._node) {
+                sound._node.volume = sound._volume * vol;
+              }
+            }
+          }
+        }
+
+        return self;
+      }
+
+      return self._volume;
+    },
+
+    /**
+     * Handle muting and unmuting globally.
+     * @param  {Boolean} muted Is muted or not.
+     */
+    mute: function(muted) {
+      var self = this || Howler;
+
+      // If we don't have an AudioContext created yet, run the setup.
+      if (!self.ctx) {
+        setupAudioContext();
+      }
+
+      self._muted = muted;
+
+      // With Web Audio, we just need to mute the master gain.
+      if (self.usingWebAudio) {
+        self.masterGain.gain.setValueAtTime(muted ? 0 : self._volume, Howler.ctx.currentTime);
+      }
+
+      // Loop through and mute all HTML5 Audio nodes.
+      for (var i=0; i<self._howls.length; i++) {
+        if (!self._howls[i]._webAudio) {
+          // Get all of the sounds in this Howl group.
+          var ids = self._howls[i]._getSoundIds();
+
+          // Loop through all sounds and mark the audio node as muted.
+          for (var j=0; j<ids.length; j++) {
+            var sound = self._howls[i]._soundById(ids[j]);
+
+            if (sound && sound._node) {
+              sound._node.muted = (muted) ? true : sound._muted;
+            }
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Handle stopping all sounds globally.
+     */
+    stop: function() {
+      var self = this || Howler;
+
+      // Loop through all Howls and stop them.
+      for (var i=0; i<self._howls.length; i++) {
+        self._howls[i].stop();
+      }
+
+      return self;
+    },
+
+    /**
+     * Unload and destroy all currently loaded Howl objects.
+     * @return {Howler}
+     */
+    unload: function() {
+      var self = this || Howler;
+
+      for (var i=self._howls.length-1; i>=0; i--) {
+        self._howls[i].unload();
+      }
+
+      // Create a new AudioContext to make sure it is fully reset.
+      if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') {
+        self.ctx.close();
+        self.ctx = null;
+        setupAudioContext();
+      }
+
+      return self;
+    },
+
+    /**
+     * Check for codec support of specific extension.
+     * @param  {String} ext Audio file extention.
+     * @return {Boolean}
+     */
+    codecs: function(ext) {
+      return (this || Howler)._codecs[ext.replace(/^x-/, '')];
+    },
+
+    /**
+     * Setup various state values for global tracking.
+     * @return {Howler}
+     */
+    _setup: function() {
+      var self = this || Howler;
+
+      // Keeps track of the suspend/resume state of the AudioContext.
+      self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended';
+
+      // Automatically begin the 30-second suspend process
+      self._autoSuspend();
+
+      // Check if audio is available.
+      if (!self.usingWebAudio) {
+        // No audio is available on this system if noAudio is set to true.
+        if (typeof Audio !== 'undefined') {
+          try {
+            var test = new Audio();
+
+            // Check if the canplaythrough event is available.
+            if (typeof test.oncanplaythrough === 'undefined') {
+              self._canPlayEvent = 'canplay';
+            }
+          } catch(e) {
+            self.noAudio = true;
+          }
+        } else {
+          self.noAudio = true;
+        }
+      }
+
+      // Test to make sure audio isn't disabled in Internet Explorer.
+      try {
+        var test = new Audio();
+        if (test.muted) {
+          self.noAudio = true;
+        }
+      } catch (e) {}
+
+      // Check for supported codecs.
+      if (!self.noAudio) {
+        self._setupCodecs();
+      }
+
+      return self;
+    },
+
+    /**
+     * Check for browser support for various codecs and cache the results.
+     * @return {Howler}
+     */
+    _setupCodecs: function() {
+      var self = this || Howler;
+      var audioTest = null;
+
+      // Must wrap in a try/catch because IE11 in server mode throws an error.
+      try {
+        audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
+      } catch (err) {
+        return self;
+      }
+
+      if (!audioTest || typeof audioTest.canPlayType !== 'function') {
+        return self;
+      }
+
+      var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
+
+      // Opera version <33 has mixed MP3 support, so we need to check for and block it.
+      var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g);
+      var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);
+
+      self._codecs = {
+        mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
+        mpeg: !!mpegTest,
+        opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
+        ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
+        oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
+        wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''),
+        aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
+        caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
+        m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
+        m4b: !!(audioTest.canPlayType('audio/x-m4b;') || audioTest.canPlayType('audio/m4b;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
+        mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
+        weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
+        webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
+        dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
+        flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
+      };
+
+      return self;
+    },
+
+    /**
+     * Some browsers/devices will only allow audio to be played after a user interaction.
+     * Attempt to automatically unlock audio on the first user interaction.
+     * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
+     * @return {Howler}
+     */
+    _unlockAudio: function() {
+      var self = this || Howler;
+
+      // Only run this if Web Audio is supported and it hasn't already been unlocked.
+      if (self._audioUnlocked || !self.ctx) {
+        return;
+      }
+
+      self._audioUnlocked = false;
+      self.autoUnlock = false;
+
+      // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views.
+      // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000.
+      // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate.
+      if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) {
+        self._mobileUnloaded = true;
+        self.unload();
+      }
+
+      // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per:
+      // http://stackoverflow.com/questions/24119684
+      self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050);
+
+      // Call this method on touch start to create and play a buffer,
+      // then check if the audio actually played to determine if
+      // audio has now been unlocked on iOS, Android, etc.
+      var unlock = function(e) {
+        // Create a pool of unlocked HTML5 Audio objects that can
+        // be used for playing sounds without user interaction. HTML5
+        // Audio objects must be individually unlocked, as opposed
+        // to the WebAudio API which only needs a single activation.
+        // This must occur before WebAudio setup or the source.onended
+        // event will not fire.
+        while (self._html5AudioPool.length < self.html5PoolSize) {
+          try {
+            var audioNode = new Audio();
+
+            // Mark this Audio object as unlocked to ensure it can get returned
+            // to the unlocked pool when released.
+            audioNode._unlocked = true;
+
+            // Add the audio node to the pool.
+            self._releaseHtml5Audio(audioNode);
+          } catch (e) {
+            self.noAudio = true;
+            break;
+          }
+        }
+
+        // Loop through any assigned audio nodes and unlock them.
+        for (var i=0; i<self._howls.length; i++) {
+          if (!self._howls[i]._webAudio) {
+            // Get all of the sounds in this Howl group.
+            var ids = self._howls[i]._getSoundIds();
+
+            // Loop through all sounds and unlock the audio nodes.
+            for (var j=0; j<ids.length; j++) {
+              var sound = self._howls[i]._soundById(ids[j]);
+
+              if (sound && sound._node && !sound._node._unlocked) {
+                sound._node._unlocked = true;
+                sound._node.load();
+              }
+            }
+          }
+        }
+
+        // Fix Android can not play in suspend state.
+        self._autoResume();
+
+        // Create an empty buffer.
+        var source = self.ctx.createBufferSource();
+        source.buffer = self._scratchBuffer;
+        source.connect(self.ctx.destination);
+
+        // Play the empty buffer.
+        if (typeof source.start === 'undefined') {
+          source.noteOn(0);
+        } else {
+          source.start(0);
+        }
+
+        // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
+        if (typeof self.ctx.resume === 'function') {
+          self.ctx.resume();
+        }
+
+        // Setup a timeout to check that we are unlocked on the next event loop.
+        source.onended = function() {
+          source.disconnect(0);
+
+          // Update the unlocked state and prevent this check from happening again.
+          self._audioUnlocked = true;
+
+          // Remove the touch start listener.
+          document.removeEventListener('touchstart', unlock, true);
+          document.removeEventListener('touchend', unlock, true);
+          document.removeEventListener('click', unlock, true);
+
+          // Let all sounds know that audio has been unlocked.
+          for (var i=0; i<self._howls.length; i++) {
+            self._howls[i]._emit('unlock');
+          }
+        };
+      };
+
+      // Setup a touch start listener to attempt an unlock in.
+      document.addEventListener('touchstart', unlock, true);
+      document.addEventListener('touchend', unlock, true);
+      document.addEventListener('click', unlock, true);
+
+      return self;
+    },
+
+    /**
+     * Get an unlocked HTML5 Audio object from the pool. If none are left,
+     * return a new Audio object and throw a warning.
+     * @return {Audio} HTML5 Audio object.
+     */
+    _obtainHtml5Audio: function() {
+      var self = this || Howler;
+
+      // Return the next object from the pool if one exists.
+      if (self._html5AudioPool.length) {
+        return self._html5AudioPool.pop();
+      }
+
+      //.Check if the audio is locked and throw a warning.
+      var testPlay = new Audio().play();
+      if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) {
+        testPlay.catch(function() {
+          console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.');
+        });
+      }
+
+      return new Audio();
+    },
+
+    /**
+     * Return an activated HTML5 Audio object to the pool.
+     * @return {Howler}
+     */
+    _releaseHtml5Audio: function(audio) {
+      var self = this || Howler;
+
+      // Don't add audio to the pool if we don't know if it has been unlocked.
+      if (audio._unlocked) {
+        self._html5AudioPool.push(audio);
+      }
+
+      return self;
+    },
+
+    /**
+     * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
+     * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
+     * @return {Howler}
+     */
+    _autoSuspend: function() {
+      var self = this;
+
+      if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) {
+        return;
+      }
+
+      // Check if any sounds are playing.
+      for (var i=0; i<self._howls.length; i++) {
+        if (self._howls[i]._webAudio) {
+          for (var j=0; j<self._howls[i]._sounds.length; j++) {
+            if (!self._howls[i]._sounds[j]._paused) {
+              return self;
+            }
+          }
+        }
+      }
+
+      if (self._suspendTimer) {
+        clearTimeout(self._suspendTimer);
+      }
+
+      // If no sound has played after 30 seconds, suspend the context.
+      self._suspendTimer = setTimeout(function() {
+        if (!self.autoSuspend) {
+          return;
+        }
+
+        self._suspendTimer = null;
+        self.state = 'suspending';
+
+        // Handle updating the state of the audio context after suspending.
+        var handleSuspension = function() {
+          self.state = 'suspended';
+
+          if (self._resumeAfterSuspend) {
+            delete self._resumeAfterSuspend;
+            self._autoResume();
+          }
+        };
+
+        // Either the state gets suspended or it is interrupted.
+        // Either way, we need to update the state to suspended.
+        self.ctx.suspend().then(handleSuspension, handleSuspension);
+      }, 30000);
+
+      return self;
+    },
+
+    /**
+     * Automatically resume the Web Audio AudioContext when a new sound is played.
+     * @return {Howler}
+     */
+    _autoResume: function() {
+      var self = this;
+
+      if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) {
+        return;
+      }
+
+      if (self.state === 'running' && self.ctx.state !== 'interrupted' && self._suspendTimer) {
+        clearTimeout(self._suspendTimer);
+        self._suspendTimer = null;
+      } else if (self.state === 'suspended' || self.state === 'running' && self.ctx.state === 'interrupted') {
+        self.ctx.resume().then(function() {
+          self.state = 'running';
+
+          // Emit to all Howls that the audio has resumed.
+          for (var i=0; i<self._howls.length; i++) {
+            self._howls[i]._emit('resume');
+          }
+        });
+
+        if (self._suspendTimer) {
+          clearTimeout(self._suspendTimer);
+          self._suspendTimer = null;
+        }
+      } else if (self.state === 'suspending') {
+        self._resumeAfterSuspend = true;
+      }
+
+      return self;
+    }
+  };
+
+  // Setup the global audio controller.
+  var Howler = new HowlerGlobal();
+
+  /** Group Methods **/
+  /***************************************************************************/
+
+  /**
+   * Create an audio group controller.
+   * @param {Object} o Passed in properties for this group.
+   */
+  var Howl = function(o) {
+    var self = this;
+
+    // Throw an error if no source is provided.
+    if (!o.src || o.src.length === 0) {
+      console.error('An array of source files must be passed with any new Howl.');
+      return;
+    }
+
+    self.init(o);
+  };
+  Howl.prototype = {
+    /**
+     * Initialize a new Howl group object.
+     * @param  {Object} o Passed in properties for this group.
+     * @return {Howl}
+     */
+    init: function(o) {
+      var self = this;
+
+      // If we don't have an AudioContext created yet, run the setup.
+      if (!Howler.ctx) {
+        setupAudioContext();
+      }
+
+      // Setup user-defined default properties.
+      self._autoplay = o.autoplay || false;
+      self._format = (typeof o.format !== 'string') ? o.format : [o.format];
+      self._html5 = o.html5 || false;
+      self._muted = o.mute || false;
+      self._loop = o.loop || false;
+      self._pool = o.pool || 5;
+      self._preload = (typeof o.preload === 'boolean' || o.preload === 'metadata') ? o.preload : true;
+      self._rate = o.rate || 1;
+      self._sprite = o.sprite || {};
+      self._src = (typeof o.src !== 'string') ? o.src : [o.src];
+      self._volume = o.volume !== undefined ? o.volume : 1;
+      self._xhr = {
+        method: o.xhr && o.xhr.method ? o.xhr.method : 'GET',
+        headers: o.xhr && o.xhr.headers ? o.xhr.headers : null,
+        withCredentials: o.xhr && o.xhr.withCredentials ? o.xhr.withCredentials : false,
+      };
+
+      // Setup all other default properties.
+      self._duration = 0;
+      self._state = 'unloaded';
+      self._sounds = [];
+      self._endTimers = {};
+      self._queue = [];
+      self._playLock = false;
+
+      // Setup event listeners.
+      self._onend = o.onend ? [{fn: o.onend}] : [];
+      self._onfade = o.onfade ? [{fn: o.onfade}] : [];
+      self._onload = o.onload ? [{fn: o.onload}] : [];
+      self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
+      self._onplayerror = o.onplayerror ? [{fn: o.onplayerror}] : [];
+      self._onpause = o.onpause ? [{fn: o.onpause}] : [];
+      self._onplay = o.onplay ? [{fn: o.onplay}] : [];
+      self._onstop = o.onstop ? [{fn: o.onstop}] : [];
+      self._onmute = o.onmute ? [{fn: o.onmute}] : [];
+      self._onvolume = o.onvolume ? [{fn: o.onvolume}] : [];
+      self._onrate = o.onrate ? [{fn: o.onrate}] : [];
+      self._onseek = o.onseek ? [{fn: o.onseek}] : [];
+      self._onunlock = o.onunlock ? [{fn: o.onunlock}] : [];
+      self._onresume = [];
+
+      // Web Audio or HTML5 Audio?
+      self._webAudio = Howler.usingWebAudio && !self._html5;
+
+      // Automatically try to enable audio.
+      if (typeof Howler.ctx !== 'undefined' && Howler.ctx && Howler.autoUnlock) {
+        Howler._unlockAudio();
+      }
+
+      // Keep track of this Howl group in the global controller.
+      Howler._howls.push(self);
+
+      // If they selected autoplay, add a play event to the load queue.
+      if (self._autoplay) {
+        self._queue.push({
+          event: 'play',
+          action: function() {
+            self.play();
+          }
+        });
+      }
+
+      // Load the source file unless otherwise specified.
+      if (self._preload && self._preload !== 'none') {
+        self.load();
+      }
+
+      return self;
+    },
+
+    /**
+     * Load the audio file.
+     * @return {Howler}
+     */
+    load: function() {
+      var self = this;
+      var url = null;
+
+      // If no audio is available, quit immediately.
+      if (Howler.noAudio) {
+        self._emit('loaderror', null, 'No audio support.');
+        return;
+      }
+
+      // Make sure our source is in an array.
+      if (typeof self._src === 'string') {
+        self._src = [self._src];
+      }
+
+      // Loop through the sources and pick the first one that is compatible.
+      for (var i=0; i<self._src.length; i++) {
+        var ext, str;
+
+        if (self._format && self._format[i]) {
+          // If an extension was specified, use that instead.
+          ext = self._format[i];
+        } else {
+          // Make sure the source is a string.
+          str = self._src[i];
+          if (typeof str !== 'string') {
+            self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.');
+            continue;
+          }
+
+          // Extract the file extension from the URL or base64 data URI.
+          ext = /^data:audio\/([^;,]+);/i.exec(str);
+          if (!ext) {
+            ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]);
+          }
+
+          if (ext) {
+            ext = ext[1].toLowerCase();
+          }
+        }
+
+        // Log a warning if no extension was found.
+        if (!ext) {
+          console.warn('No file extension was found. Consider using the "format" property or specify an extension.');
+        }
+
+        // Check if this extension is available.
+        if (ext && Howler.codecs(ext)) {
+          url = self._src[i];
+          break;
+        }
+      }
+
+      if (!url) {
+        self._emit('loaderror', null, 'No codec support for selected audio sources.');
+        return;
+      }
+
+      self._src = url;
+      self._state = 'loading';
+
+      // If the hosting page is HTTPS and the source isn't,
+      // drop down to HTML5 Audio to avoid Mixed Content errors.
+      if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') {
+        self._html5 = true;
+        self._webAudio = false;
+      }
+
+      // Create a new sound object and add it to the pool.
+      new Sound(self);
+
+      // Load and decode the audio data for playback.
+      if (self._webAudio) {
+        loadBuffer(self);
+      }
+
+      return self;
+    },
+
+    /**
+     * Play a sound or resume previous playback.
+     * @param  {String/Number} sprite   Sprite name for sprite playback or sound id to continue previous.
+     * @param  {Boolean} internal Internal Use: true prevents event firing.
+     * @return {Number}          Sound ID.
+     */
+    play: function(sprite, internal) {
+      var self = this;
+      var id = null;
+
+      // Determine if a sprite, sound id or nothing was passed
+      if (typeof sprite === 'number') {
+        id = sprite;
+        sprite = null;
+      } else if (typeof sprite === 'string' && self._state === 'loaded' && !self._sprite[sprite]) {
+        // If the passed sprite doesn't exist, do nothing.
+        return null;
+      } else if (typeof sprite === 'undefined') {
+        // Use the default sound sprite (plays the full audio length).
+        sprite = '__default';
+
+        // Check if there is a single paused sound that isn't ended.
+        // If there is, play that sound. If not, continue as usual.
+        if (!self._playLock) {
+          var num = 0;
+          for (var i=0; i<self._sounds.length; i++) {
+            if (self._sounds[i]._paused && !self._sounds[i]._ended) {
+              num++;
+              id = self._sounds[i]._id;
+            }
+          }
+
+          if (num === 1) {
+            sprite = null;
+          } else {
+            id = null;
+          }
+        }
+      }
+
+      // Get the selected node, or get one from the pool.
+      var sound = id ? self._soundById(id) : self._inactiveSound();
+
+      // If the sound doesn't exist, do nothing.
+      if (!sound) {
+        return null;
+      }
+
+      // Select the sprite definition.
+      if (id && !sprite) {
+        sprite = sound._sprite || '__default';
+      }
+
+      // If the sound hasn't loaded, we must wait to get the audio's duration.
+      // We also need to wait to make sure we don't run into race conditions with
+      // the order of function calls.
+      if (self._state !== 'loaded') {
+        // Set the sprite value on this sound.
+        sound._sprite = sprite;
+
+        // Mark this sound as not ended in case another sound is played before this one loads.
+        sound._ended = false;
+
+        // Add the sound to the queue to be played on load.
+        var soundId = sound._id;
+        self._queue.push({
+          event: 'play',
+          action: function() {
+            self.play(soundId);
+          }
+        });
+
+        return soundId;
+      }
+
+      // Don't play the sound if an id was passed and it is already playing.
+      if (id && !sound._paused) {
+        // Trigger the play event, in order to keep iterating through queue.
+        if (!internal) {
+          self._loadQueue('play');
+        }
+
+        return sound._id;
+      }
+
+      // Make sure the AudioContext isn't suspended, and resume it if it is.
+      if (self._webAudio) {
+        Howler._autoResume();
+      }
+
+      // Determine how long to play for and where to start playing.
+      var seek = Math.max(0, sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000);
+      var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek);
+      var timeout = (duration * 1000) / Math.abs(sound._rate);
+      var start = self._sprite[sprite][0] / 1000;
+      var stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
+      sound._sprite = sprite;
+
+      // Mark the sound as ended instantly so that this async playback
+      // doesn't get grabbed by another call to play while this one waits to start.
+      sound._ended = false;
+
+      // Update the parameters of the sound.
+      var setParams = function() {
+        sound._paused = false;
+        sound._seek = seek;
+        sound._start = start;
+        sound._stop = stop;
+        sound._loop = !!(sound._loop || self._sprite[sprite][2]);
+      };
+
+      // End the sound instantly if seek is at the end.
+      if (seek >= stop) {
+        self._ended(sound);
+        return;
+      }
+
+      // Begin the actual playback.
+      var node = sound._node;
+      if (self._webAudio) {
+        // Fire this when the sound is ready to play to begin Web Audio playback.
+        var playWebAudio = function() {
+          self._playLock = false;
+          setParams();
+          self._refreshBuffer(sound);
+
+          // Setup the playback params.
+          var vol = (sound._muted || self._muted) ? 0 : sound._volume;
+          node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
+          sound._playStart = Howler.ctx.currentTime;
+
+          // Play the sound using the supported method.
+          if (typeof node.bufferSource.start === 'undefined') {
+            sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
+          } else {
+            sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
+          }
+
+          // Start a new timer if none is present.
+          if (timeout !== Infinity) {
+            self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
+          }
+
+          if (!internal) {
+            setTimeout(function() {
+              self._emit('play', sound._id);
+              self._loadQueue();
+            }, 0);
+          }
+        };
+
+        if (Howler.state === 'running' && Howler.ctx.state !== 'interrupted') {
+          playWebAudio();
+        } else {
+          self._playLock = true;
+
+          // Wait for the audio context to resume before playing.
+          self.once('resume', playWebAudio);
+
+          // Cancel the end timer.
+          self._clearTimer(sound._id);
+        }
+      } else {
+        // Fire this when the sound is ready to play to begin HTML5 Audio playback.
+        var playHtml5 = function() {
+          node.currentTime = seek;
+          node.muted = sound._muted || self._muted || Howler._muted || node.muted;
+          node.volume = sound._volume * Howler.volume();
+          node.playbackRate = sound._rate;
+
+          // Some browsers will throw an error if this is called without user interaction.
+          try {
+            var play = node.play();
+
+            // Support older browsers that don't support promises, and thus don't have this issue.
+            if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
+              // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
+              self._playLock = true;
+
+              // Set param values immediately.
+              setParams();
+
+              // Releases the lock and executes queued actions.
+              play
+                .then(function() {
+                  self._playLock = false;
+                  node._unlocked = true;
+                  if (!internal) {
+                    self._emit('play', sound._id);
+                    self._loadQueue();
+                  }
+                })
+                .catch(function() {
+                  self._playLock = false;
+                  self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
+                    'on mobile devices and Chrome where playback was not within a user interaction.');
+
+                  // Reset the ended and paused values.
+                  sound._ended = true;
+                  sound._paused = true;
+                });
+            } else if (!internal) {
+              self._playLock = false;
+              setParams();
+              self._emit('play', sound._id);
+              self._loadQueue();
+            }
+
+            // Setting rate before playing won't work in IE, so we set it again here.
+            node.playbackRate = sound._rate;
+
+            // If the node is still paused, then we can assume there was a playback issue.
+            if (node.paused) {
+              self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
+                'on mobile devices and Chrome where playback was not within a user interaction.');
+              return;
+            }
+
+            // Setup the end timer on sprites or listen for the ended event.
+            if (sprite !== '__default' || sound._loop) {
+              self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
+            } else {
+              self._endTimers[sound._id] = function() {
+                // Fire ended on this audio node.
+                self._ended(sound);
+
+                // Clear this listener.
+                node.removeEventListener('ended', self._endTimers[sound._id], false);
+              };
+              node.addEventListener('ended', self._endTimers[sound._id], false);
+            }
+          } catch (err) {
+            self._emit('playerror', sound._id, err);
+          }
+        };
+
+        // If this is streaming audio, make sure the src is set and load again.
+        if (node.src === 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA') {
+          node.src = self._src;
+          node.load();
+        }
+
+        // Play immediately if ready, or wait for the 'canplaythrough'e vent.
+        var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS);
+        if (node.readyState >= 3 || loadedNoReadyState) {
+          playHtml5();
+        } else {
+          self._playLock = true;
+
+          var listener = function() {
+            // Begin playback.
+            playHtml5();
+
+            // Clear this listener.
+            node.removeEventListener(Howler._canPlayEvent, listener, false);
+          };
+          node.addEventListener(Howler._canPlayEvent, listener, false);
+
+          // Cancel the end timer.
+          self._clearTimer(sound._id);
+        }
+      }
+
+      return sound._id;
+    },
+
+    /**
+     * Pause playback and save current position.
+     * @param  {Number} id The sound ID (empty to pause all in group).
+     * @return {Howl}
+     */
+    pause: function(id) {
+      var self = this;
+
+      // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'pause',
+          action: function() {
+            self.pause(id);
+          }
+        });
+
+        return self;
+      }
+
+      // If no id is passed, get all ID's to be paused.
+      var ids = self._getSoundIds(id);
+
+      for (var i=0; i<ids.length; i++) {
+        // Clear the end timer.
+        self._clearTimer(ids[i]);
+
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        if (sound && !sound._paused) {
+          // Reset the seek position.
+          sound._seek = self.seek(ids[i]);
+          sound._rateSeek = 0;
+          sound._paused = true;
+
+          // Stop currently running fades.
+          self._stopFade(ids[i]);
+
+          if (sound._node) {
+            if (self._webAudio) {
+              // Make sure the sound has been created.
+              if (!sound._node.bufferSource) {
+                continue;
+              }
+
+              if (typeof sound._node.bufferSource.stop === 'undefined') {
+                sound._node.bufferSource.noteOff(0);
+              } else {
+                sound._node.bufferSource.stop(0);
+              }
+
+              // Clean up the buffer source.
+              self._cleanBuffer(sound._node);
+            } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
+              sound._node.pause();
+            }
+          }
+        }
+
+        // Fire the pause event, unless `true` is passed as the 2nd argument.
+        if (!arguments[1]) {
+          self._emit('pause', sound ? sound._id : null);
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Stop playback and reset to start.
+     * @param  {Number} id The sound ID (empty to stop all in group).
+     * @param  {Boolean} internal Internal Use: true prevents event firing.
+     * @return {Howl}
+     */
+    stop: function(id, internal) {
+      var self = this;
+
+      // If the sound hasn't loaded, add it to the load queue to stop when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'stop',
+          action: function() {
+            self.stop(id);
+          }
+        });
+
+        return self;
+      }
+
+      // If no id is passed, get all ID's to be stopped.
+      var ids = self._getSoundIds(id);
+
+      for (var i=0; i<ids.length; i++) {
+        // Clear the end timer.
+        self._clearTimer(ids[i]);
+
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        if (sound) {
+          // Reset the seek position.
+          sound._seek = sound._start || 0;
+          sound._rateSeek = 0;
+          sound._paused = true;
+          sound._ended = true;
+
+          // Stop currently running fades.
+          self._stopFade(ids[i]);
+
+          if (sound._node) {
+            if (self._webAudio) {
+              // Make sure the sound's AudioBufferSourceNode has been created.
+              if (sound._node.bufferSource) {
+                if (typeof sound._node.bufferSource.stop === 'undefined') {
+                  sound._node.bufferSource.noteOff(0);
+                } else {
+                  sound._node.bufferSource.stop(0);
+                }
+
+                // Clean up the buffer source.
+                self._cleanBuffer(sound._node);
+              }
+            } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
+              sound._node.currentTime = sound._start || 0;
+              sound._node.pause();
+
+              // If this is a live stream, stop download once the audio is stopped.
+              if (sound._node.duration === Infinity) {
+                self._clearSound(sound._node);
+              }
+            }
+          }
+
+          if (!internal) {
+            self._emit('stop', sound._id);
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Mute/unmute a single sound or all sounds in this Howl group.
+     * @param  {Boolean} muted Set to true to mute and false to unmute.
+     * @param  {Number} id    The sound ID to update (omit to mute/unmute all).
+     * @return {Howl}
+     */
+    mute: function(muted, id) {
+      var self = this;
+
+      // If the sound hasn't loaded, add it to the load queue to mute when capable.
+      if (self._state !== 'loaded'|| self._playLock) {
+        self._queue.push({
+          event: 'mute',
+          action: function() {
+            self.mute(muted, id);
+          }
+        });
+
+        return self;
+      }
+
+      // If applying mute/unmute to all sounds, update the group's value.
+      if (typeof id === 'undefined') {
+        if (typeof muted === 'boolean') {
+          self._muted = muted;
+        } else {
+          return self._muted;
+        }
+      }
+
+      // If no id is passed, get all ID's to be muted.
+      var ids = self._getSoundIds(id);
+
+      for (var i=0; i<ids.length; i++) {
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        if (sound) {
+          sound._muted = muted;
+
+          // Cancel active fade and set the volume to the end value.
+          if (sound._interval) {
+            self._stopFade(sound._id);
+          }
+
+          if (self._webAudio && sound._node) {
+            sound._node.gain.setValueAtTime(muted ? 0 : sound._volume, Howler.ctx.currentTime);
+          } else if (sound._node) {
+            sound._node.muted = Howler._muted ? true : muted;
+          }
+
+          self._emit('mute', sound._id);
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the volume of this sound or of the Howl group. This method can optionally take 0, 1 or 2 arguments.
+     *   volume() -> Returns the group's volume value.
+     *   volume(id) -> Returns the sound id's current volume.
+     *   volume(vol) -> Sets the volume of all sounds in this Howl group.
+     *   volume(vol, id) -> Sets the volume of passed sound id.
+     * @return {Howl/Number} Returns self or current volume.
+     */
+    volume: function() {
+      var self = this;
+      var args = arguments;
+      var vol, id;
+
+      // Determine the values based on arguments.
+      if (args.length === 0) {
+        // Return the value of the groups' volume.
+        return self._volume;
+      } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') {
+        // First check if this is an ID, and if not, assume it is a new volume.
+        var ids = self._getSoundIds();
+        var index = ids.indexOf(args[0]);
+        if (index >= 0) {
+          id = parseInt(args[0], 10);
+        } else {
+          vol = parseFloat(args[0]);
+        }
+      } else if (args.length >= 2) {
+        vol = parseFloat(args[0]);
+        id = parseInt(args[1], 10);
+      }
+
+      // Update the volume or return the current volume.
+      var sound;
+      if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
+        // If the sound hasn't loaded, add it to the load queue to change volume when capable.
+        if (self._state !== 'loaded'|| self._playLock) {
+          self._queue.push({
+            event: 'volume',
+            action: function() {
+              self.volume.apply(self, args);
+            }
+          });
+
+          return self;
+        }
+
+        // Set the group volume.
+        if (typeof id === 'undefined') {
+          self._volume = vol;
+        }
+
+        // Update one or all volumes.
+        id = self._getSoundIds(id);
+        for (var i=0; i<id.length; i++) {
+          // Get the sound.
+          sound = self._soundById(id[i]);
+
+          if (sound) {
+            sound._volume = vol;
+
+            // Stop currently running fades.
+            if (!args[2]) {
+              self._stopFade(id[i]);
+            }
+
+            if (self._webAudio && sound._node && !sound._muted) {
+              sound._node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
+            } else if (sound._node && !sound._muted) {
+              sound._node.volume = vol * Howler.volume();
+            }
+
+            self._emit('volume', sound._id);
+          }
+        }
+      } else {
+        sound = id ? self._soundById(id) : self._sounds[0];
+        return sound ? sound._volume : 0;
+      }
+
+      return self;
+    },
+
+    /**
+     * Fade a currently playing sound between two volumes (if no id is passed, all sounds will fade).
+     * @param  {Number} from The value to fade from (0.0 to 1.0).
+     * @param  {Number} to   The volume to fade to (0.0 to 1.0).
+     * @param  {Number} len  Time in milliseconds to fade.
+     * @param  {Number} id   The sound id (omit to fade all sounds).
+     * @return {Howl}
+     */
+    fade: function(from, to, len, id) {
+      var self = this;
+
+      // If the sound hasn't loaded, add it to the load queue to fade when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'fade',
+          action: function() {
+            self.fade(from, to, len, id);
+          }
+        });
+
+        return self;
+      }
+
+      // Make sure the to/from/len values are numbers.
+      from = Math.min(Math.max(0, parseFloat(from)), 1);
+      to = Math.min(Math.max(0, parseFloat(to)), 1);
+      len = parseFloat(len);
+
+      // Set the volume to the start position.
+      self.volume(from, id);
+
+      // Fade the volume of one or all sounds.
+      var ids = self._getSoundIds(id);
+      for (var i=0; i<ids.length; i++) {
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        // Create a linear fade or fall back to timeouts with HTML5 Audio.
+        if (sound) {
+          // Stop the previous fade if no sprite is being used (otherwise, volume handles this).
+          if (!id) {
+            self._stopFade(ids[i]);
+          }
+
+          // If we are using Web Audio, let the native methods do the actual fade.
+          if (self._webAudio && !sound._muted) {
+            var currentTime = Howler.ctx.currentTime;
+            var end = currentTime + (len / 1000);
+            sound._volume = from;
+            sound._node.gain.setValueAtTime(from, currentTime);
+            sound._node.gain.linearRampToValueAtTime(to, end);
+          }
+
+          self._startFadeInterval(sound, from, to, len, ids[i], typeof id === 'undefined');
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Starts the internal interval to fade a sound.
+     * @param  {Object} sound Reference to sound to fade.
+     * @param  {Number} from The value to fade from (0.0 to 1.0).
+     * @param  {Number} to   The volume to fade to (0.0 to 1.0).
+     * @param  {Number} len  Time in milliseconds to fade.
+     * @param  {Number} id   The sound id to fade.
+     * @param  {Boolean} isGroup   If true, set the volume on the group.
+     */
+    _startFadeInterval: function(sound, from, to, len, id, isGroup) {
+      var self = this;
+      var vol = from;
+      var diff = to - from;
+      var steps = Math.abs(diff / 0.01);
+      var stepLen = Math.max(4, (steps > 0) ? len / steps : len);
+      var lastTick = Date.now();
+
+      // Store the value being faded to.
+      sound._fadeTo = to;
+
+      // Update the volume value on each interval tick.
+      sound._interval = setInterval(function() {
+        // Update the volume based on the time since the last tick.
+        var tick = (Date.now() - lastTick) / len;
+        lastTick = Date.now();
+        vol += diff * tick;
+
+        // Make sure the volume is in the right bounds.
+        if (diff < 0) {
+          vol = Math.max(to, vol);
+        } else {
+          vol = Math.min(to, vol);
+        }
+
+        // Round to within 2 decimal points.
+        vol = Math.round(vol * 100) / 100;
+
+        // Change the volume.
+        if (self._webAudio) {
+          sound._volume = vol;
+        } else {
+          self.volume(vol, sound._id, true);
+        }
+
+        // Set the group's volume.
+        if (isGroup) {
+          self._volume = vol;
+        }
+
+        // When the fade is complete, stop it and fire event.
+        if ((to < from && vol <= to) || (to > from && vol >= to)) {
+          clearInterval(sound._interval);
+          sound._interval = null;
+          sound._fadeTo = null;
+          self.volume(to, sound._id);
+          self._emit('fade', sound._id);
+        }
+      }, stepLen);
+    },
+
+    /**
+     * Internal method that stops the currently playing fade when
+     * a new fade starts, volume is changed or the sound is stopped.
+     * @param  {Number} id The sound id.
+     * @return {Howl}
+     */
+    _stopFade: function(id) {
+      var self = this;
+      var sound = self._soundById(id);
+
+      if (sound && sound._interval) {
+        if (self._webAudio) {
+          sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime);
+        }
+
+        clearInterval(sound._interval);
+        sound._interval = null;
+        self.volume(sound._fadeTo, id);
+        sound._fadeTo = null;
+        self._emit('fade', id);
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
+     *   loop() -> Returns the group's loop value.
+     *   loop(id) -> Returns the sound id's loop value.
+     *   loop(loop) -> Sets the loop value for all sounds in this Howl group.
+     *   loop(loop, id) -> Sets the loop value of passed sound id.
+     * @return {Howl/Boolean} Returns self or current loop value.
+     */
+    loop: function() {
+      var self = this;
+      var args = arguments;
+      var loop, id, sound;
+
+      // Determine the values for loop and id.
+      if (args.length === 0) {
+        // Return the grou's loop value.
+        return self._loop;
+      } else if (args.length === 1) {
+        if (typeof args[0] === 'boolean') {
+          loop = args[0];
+          self._loop = loop;
+        } else {
+          // Return this sound's loop value.
+          sound = self._soundById(parseInt(args[0], 10));
+          return sound ? sound._loop : false;
+        }
+      } else if (args.length === 2) {
+        loop = args[0];
+        id = parseInt(args[1], 10);
+      }
+
+      // If no id is passed, get all ID's to be looped.
+      var ids = self._getSoundIds(id);
+      for (var i=0; i<ids.length; i++) {
+        sound = self._soundById(ids[i]);
+
+        if (sound) {
+          sound._loop = loop;
+          if (self._webAudio && sound._node && sound._node.bufferSource) {
+            sound._node.bufferSource.loop = loop;
+            if (loop) {
+              sound._node.bufferSource.loopStart = sound._start || 0;
+              sound._node.bufferSource.loopEnd = sound._stop;
+            }
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the playback rate of a sound. This method can optionally take 0, 1 or 2 arguments.
+     *   rate() -> Returns the first sound node's current playback rate.
+     *   rate(id) -> Returns the sound id's current playback rate.
+     *   rate(rate) -> Sets the playback rate of all sounds in this Howl group.
+     *   rate(rate, id) -> Sets the playback rate of passed sound id.
+     * @return {Howl/Number} Returns self or the current playback rate.
+     */
+    rate: function() {
+      var self = this;
+      var args = arguments;
+      var rate, id;
+
+      // Determine the values based on arguments.
+      if (args.length === 0) {
+        // We will simply return the current rate of the first node.
+        id = self._sounds[0]._id;
+      } else if (args.length === 1) {
+        // First check if this is an ID, and if not, assume it is a new rate value.
+        var ids = self._getSoundIds();
+        var index = ids.indexOf(args[0]);
+        if (index >= 0) {
+          id = parseInt(args[0], 10);
+        } else {
+          rate = parseFloat(args[0]);
+        }
+      } else if (args.length === 2) {
+        rate = parseFloat(args[0]);
+        id = parseInt(args[1], 10);
+      }
+
+      // Update the playback rate or return the current value.
+      var sound;
+      if (typeof rate === 'number') {
+        // If the sound hasn't loaded, add it to the load queue to change playback rate when capable.
+        if (self._state !== 'loaded' || self._playLock) {
+          self._queue.push({
+            event: 'rate',
+            action: function() {
+              self.rate.apply(self, args);
+            }
+          });
+
+          return self;
+        }
+
+        // Set the group rate.
+        if (typeof id === 'undefined') {
+          self._rate = rate;
+        }
+
+        // Update one or all volumes.
+        id = self._getSoundIds(id);
+        for (var i=0; i<id.length; i++) {
+          // Get the sound.
+          sound = self._soundById(id[i]);
+
+          if (sound) {
+            // Keep track of our position when the rate changed and update the playback
+            // start position so we can properly adjust the seek position for time elapsed.
+            if (self.playing(id[i])) {
+              sound._rateSeek = self.seek(id[i]);
+              sound._playStart = self._webAudio ? Howler.ctx.currentTime : sound._playStart;
+            }
+            sound._rate = rate;
+
+            // Change the playback rate.
+            if (self._webAudio && sound._node && sound._node.bufferSource) {
+              sound._node.bufferSource.playbackRate.setValueAtTime(rate, Howler.ctx.currentTime);
+            } else if (sound._node) {
+              sound._node.playbackRate = rate;
+            }
+
+            // Reset the timers.
+            var seek = self.seek(id[i]);
+            var duration = ((self._sprite[sound._sprite][0] + self._sprite[sound._sprite][1]) / 1000) - seek;
+            var timeout = (duration * 1000) / Math.abs(sound._rate);
+
+            // Start a new end timer if sound is already playing.
+            if (self._endTimers[id[i]] || !sound._paused) {
+              self._clearTimer(id[i]);
+              self._endTimers[id[i]] = setTimeout(self._ended.bind(self, sound), timeout);
+            }
+
+            self._emit('rate', sound._id);
+          }
+        }
+      } else {
+        sound = self._soundById(id);
+        return sound ? sound._rate : self._rate;
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
+     *   seek() -> Returns the first sound node's current seek position.
+     *   seek(id) -> Returns the sound id's current seek position.
+     *   seek(seek) -> Sets the seek position of the first sound node.
+     *   seek(seek, id) -> Sets the seek position of passed sound id.
+     * @return {Howl/Number} Returns self or the current seek position.
+     */
+    seek: function() {
+      var self = this;
+      var args = arguments;
+      var seek, id;
+
+      // Determine the values based on arguments.
+      if (args.length === 0) {
+        // We will simply return the current position of the first node.
+        id = self._sounds[0]._id;
+      } else if (args.length === 1) {
+        // First check if this is an ID, and if not, assume it is a new seek position.
+        var ids = self._getSoundIds();
+        var index = ids.indexOf(args[0]);
+        if (index >= 0) {
+          id = parseInt(args[0], 10);
+        } else if (self._sounds.length) {
+          id = self._sounds[0]._id;
+          seek = parseFloat(args[0]);
+        }
+      } else if (args.length === 2) {
+        seek = parseFloat(args[0]);
+        id = parseInt(args[1], 10);
+      }
+
+      // If there is no ID, bail out.
+      if (typeof id === 'undefined') {
+        return self;
+      }
+
+      // If the sound hasn't loaded, add it to the load queue to seek when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'seek',
+          action: function() {
+            self.seek.apply(self, args);
+          }
+        });
+
+        return self;
+      }
+
+      // Get the sound.
+      var sound = self._soundById(id);
+
+      if (sound) {
+        if (typeof seek === 'number' && seek >= 0) {
+          // Pause the sound and update position for restarting playback.
+          var playing = self.playing(id);
+          if (playing) {
+            self.pause(id, true);
+          }
+
+          // Move the position of the track and cancel timer.
+          sound._seek = seek;
+          sound._ended = false;
+          self._clearTimer(id);
+
+          // Update the seek position for HTML5 Audio.
+          if (!self._webAudio && sound._node && !isNaN(sound._node.duration)) {
+            sound._node.currentTime = seek;
+          }
+
+          // Seek and emit when ready.
+          var seekAndEmit = function() {
+            self._emit('seek', id);
+
+            // Restart the playback if the sound was playing.
+            if (playing) {
+              self.play(id, true);
+            }
+          };
+
+          // Wait for the play lock to be unset before emitting (HTML5 Audio).
+          if (playing && !self._webAudio) {
+            var emitSeek = function() {
+              if (!self._playLock) {
+                seekAndEmit();
+              } else {
+                setTimeout(emitSeek, 0);
+              }
+            };
+            setTimeout(emitSeek, 0);
+          } else {
+            seekAndEmit();
+          }
+        } else {
+          if (self._webAudio) {
+            var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0;
+            var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0;
+            return sound._seek + (rateSeek + realTime * Math.abs(sound._rate));
+          } else {
+            return sound._node.currentTime;
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * 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.
+     * @param  {Number}  id The sound id to check. If none is passed, the whole sound group is checked.
+     * @return {Boolean} True if playing and false if not.
+     */
+    playing: function(id) {
+      var self = this;
+
+      // Check the passed sound ID (if any).
+      if (typeof id === 'number') {
+        var sound = self._soundById(id);
+        return sound ? !sound._paused : false;
+      }
+
+      // Otherwise, loop through all sounds and check if any are playing.
+      for (var i=0; i<self._sounds.length; i++) {
+        if (!self._sounds[i]._paused) {
+          return true;
+        }
+      }
+
+      return false;
+    },
+
+    /**
+     * Get the duration of this sound. Passing a sound id will return the sprite duration.
+     * @param  {Number} id The sound id to check. If none is passed, return full source duration.
+     * @return {Number} Audio duration in seconds.
+     */
+    duration: function(id) {
+      var self = this;
+      var duration = self._duration;
+
+      // If we pass an ID, get the sound and return the sprite length.
+      var sound = self._soundById(id);
+      if (sound) {
+        duration = self._sprite[sound._sprite][1] / 1000;
+      }
+
+      return duration;
+    },
+
+    /**
+     * Returns the current loaded state of this Howl.
+     * @return {String} 'unloaded', 'loading', 'loaded'
+     */
+    state: function() {
+      return this._state;
+    },
+
+    /**
+     * Unload and destroy the current Howl object.
+     * This will immediately stop all sound instances attached to this group.
+     */
+    unload: function() {
+      var self = this;
+
+      // Stop playing any active sounds.
+      var sounds = self._sounds;
+      for (var i=0; i<sounds.length; i++) {
+        // Stop the sound if it is currently playing.
+        if (!sounds[i]._paused) {
+          self.stop(sounds[i]._id);
+        }
+
+        // Remove the source or disconnect.
+        if (!self._webAudio) {
+          // Set the source to 0-second silence to stop any downloading (except in IE).
+          self._clearSound(sounds[i]._node);
+
+          // Remove any event listeners.
+          sounds[i]._node.removeEventListener('error', sounds[i]._errorFn, false);
+          sounds[i]._node.removeEventListener(Howler._canPlayEvent, sounds[i]._loadFn, false);
+
+          // Release the Audio object back to the pool.
+          Howler._releaseHtml5Audio(sounds[i]._node);
+        }
+
+        // Empty out all of the nodes.
+        delete sounds[i]._node;
+
+        // Make sure all timers are cleared out.
+        self._clearTimer(sounds[i]._id);
+      }
+
+      // Remove the references in the global Howler object.
+      var index = Howler._howls.indexOf(self);
+      if (index >= 0) {
+        Howler._howls.splice(index, 1);
+      }
+
+      // Delete this sound from the cache (if no other Howl is using it).
+      var remCache = true;
+      for (i=0; i<Howler._howls.length; i++) {
+        if (Howler._howls[i]._src === self._src || self._src.indexOf(Howler._howls[i]._src) >= 0) {
+          remCache = false;
+          break;
+        }
+      }
+
+      if (cache && remCache) {
+        delete cache[self._src];
+      }
+
+      // Clear global errors.
+      Howler.noAudio = false;
+
+      // Clear out `self`.
+      self._state = 'unloaded';
+      self._sounds = [];
+      self = null;
+
+      return null;
+    },
+
+    /**
+     * Listen to a custom event.
+     * @param  {String}   event Event name.
+     * @param  {Function} fn    Listener to call.
+     * @param  {Number}   id    (optional) Only listen to events for this sound.
+     * @param  {Number}   once  (INTERNAL) Marks event to fire only once.
+     * @return {Howl}
+     */
+    on: function(event, fn, id, once) {
+      var self = this;
+      var events = self['_on' + event];
+
+      if (typeof fn === 'function') {
+        events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn});
+      }
+
+      return self;
+    },
+
+    /**
+     * Remove a custom event. Call without parameters to remove all events.
+     * @param  {String}   event Event name.
+     * @param  {Function} fn    Listener to remove. Leave empty to remove all.
+     * @param  {Number}   id    (optional) Only remove events for this sound.
+     * @return {Howl}
+     */
+    off: function(event, fn, id) {
+      var self = this;
+      var events = self['_on' + event];
+      var i = 0;
+
+      // Allow passing just an event and ID.
+      if (typeof fn === 'number') {
+        id = fn;
+        fn = null;
+      }
+
+      if (fn || id) {
+        // Loop through event store and remove the passed function.
+        for (i=0; i<events.length; i++) {
+          var isId = (id === events[i].id);
+          if (fn === events[i].fn && isId || !fn && isId) {
+            events.splice(i, 1);
+            break;
+          }
+        }
+      } else if (event) {
+        // Clear out all events of this type.
+        self['_on' + event] = [];
+      } else {
+        // Clear out all events of every type.
+        var keys = Object.keys(self);
+        for (i=0; i<keys.length; i++) {
+          if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) {
+            self[keys[i]] = [];
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Listen to a custom event and remove it once fired.
+     * @param  {String}   event Event name.
+     * @param  {Function} fn    Listener to call.
+     * @param  {Number}   id    (optional) Only listen to events for this sound.
+     * @return {Howl}
+     */
+    once: function(event, fn, id) {
+      var self = this;
+
+      // Setup the event listener.
+      self.on(event, fn, id, 1);
+
+      return self;
+    },
+
+    /**
+     * Emit all events of a specific type and pass the sound id.
+     * @param  {String} event Event name.
+     * @param  {Number} id    Sound ID.
+     * @param  {Number} msg   Message to go with event.
+     * @return {Howl}
+     */
+    _emit: function(event, id, msg) {
+      var self = this;
+      var events = self['_on' + event];
+
+      // Loop through event store and fire all functions.
+      for (var i=events.length-1; i>=0; i--) {
+        // Only fire the listener if the correct ID is used.
+        if (!events[i].id || events[i].id === id || event === 'load') {
+          setTimeout(function(fn) {
+            fn.call(this, id, msg);
+          }.bind(self, events[i].fn), 0);
+
+          // If this event was setup with `once`, remove it.
+          if (events[i].once) {
+            self.off(event, events[i].fn, events[i].id);
+          }
+        }
+      }
+
+      // Pass the event type into load queue so that it can continue stepping.
+      self._loadQueue(event);
+
+      return self;
+    },
+
+    /**
+     * Queue of actions initiated before the sound has loaded.
+     * These will be called in sequence, with the next only firing
+     * after the previous has finished executing (even if async like play).
+     * @return {Howl}
+     */
+    _loadQueue: function(event) {
+      var self = this;
+
+      if (self._queue.length > 0) {
+        var task = self._queue[0];
+
+        // Remove this task if a matching event was passed.
+        if (task.event === event) {
+          self._queue.shift();
+          self._loadQueue();
+        }
+
+        // Run the task if no event type is passed.
+        if (!event) {
+          task.action();
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Fired when playback ends at the end of the duration.
+     * @param  {Sound} sound The sound object to work with.
+     * @return {Howl}
+     */
+    _ended: function(sound) {
+      var self = this;
+      var sprite = sound._sprite;
+
+      // If we are using IE and there was network latency we may be clipping
+      // audio before it completes playing. Lets check the node to make sure it
+      // believes it has completed, before ending the playback.
+      if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) {
+        setTimeout(self._ended.bind(self, sound), 100);
+        return self;
+      }
+
+      // Should this sound loop?
+      var loop = !!(sound._loop || self._sprite[sprite][2]);
+
+      // Fire the ended event.
+      self._emit('end', sound._id);
+
+      // Restart the playback for HTML5 Audio loop.
+      if (!self._webAudio && loop) {
+        self.stop(sound._id, true).play(sound._id);
+      }
+
+      // Restart this timer if on a Web Audio loop.
+      if (self._webAudio && loop) {
+        self._emit('play', sound._id);
+        sound._seek = sound._start || 0;
+        sound._rateSeek = 0;
+        sound._playStart = Howler.ctx.currentTime;
+
+        var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate);
+        self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
+      }
+
+      // Mark the node as paused.
+      if (self._webAudio && !loop) {
+        sound._paused = true;
+        sound._ended = true;
+        sound._seek = sound._start || 0;
+        sound._rateSeek = 0;
+        self._clearTimer(sound._id);
+
+        // Clean up the buffer source.
+        self._cleanBuffer(sound._node);
+
+        // Attempt to auto-suspend AudioContext if no sounds are still playing.
+        Howler._autoSuspend();
+      }
+
+      // When using a sprite, end the track.
+      if (!self._webAudio && !loop) {
+        self.stop(sound._id, true);
+      }
+
+      return self;
+    },
+
+    /**
+     * Clear the end timer for a sound playback.
+     * @param  {Number} id The sound ID.
+     * @return {Howl}
+     */
+    _clearTimer: function(id) {
+      var self = this;
+
+      if (self._endTimers[id]) {
+        // Clear the timeout or remove the ended listener.
+        if (typeof self._endTimers[id] !== 'function') {
+          clearTimeout(self._endTimers[id]);
+        } else {
+          var sound = self._soundById(id);
+          if (sound && sound._node) {
+            sound._node.removeEventListener('ended', self._endTimers[id], false);
+          }
+        }
+
+        delete self._endTimers[id];
+      }
+
+      return self;
+    },
+
+    /**
+     * Return the sound identified by this ID, or return null.
+     * @param  {Number} id Sound ID
+     * @return {Object}    Sound object or null.
+     */
+    _soundById: function(id) {
+      var self = this;
+
+      // Loop through all sounds and find the one with this ID.
+      for (var i=0; i<self._sounds.length; i++) {
+        if (id === self._sounds[i]._id) {
+          return self._sounds[i];
+        }
+      }
+
+      return null;
+    },
+
+    /**
+     * Return an inactive sound from the pool or create a new one.
+     * @return {Sound} Sound playback object.
+     */
+    _inactiveSound: function() {
+      var self = this;
+
+      self._drain();
+
+      // Find the first inactive node to recycle.
+      for (var i=0; i<self._sounds.length; i++) {
+        if (self._sounds[i]._ended) {
+          return self._sounds[i].reset();
+        }
+      }
+
+      // If no inactive node was found, create a new one.
+      return new Sound(self);
+    },
+
+    /**
+     * Drain excess inactive sounds from the pool.
+     */
+    _drain: function() {
+      var self = this;
+      var limit = self._pool;
+      var cnt = 0;
+      var i = 0;
+
+      // If there are less sounds than the max pool size, we are done.
+      if (self._sounds.length < limit) {
+        return;
+      }
+
+      // Count the number of inactive sounds.
+      for (i=0; i<self._sounds.length; i++) {
+        if (self._sounds[i]._ended) {
+          cnt++;
+        }
+      }
+
+      // Remove excess inactive sounds, going in reverse order.
+      for (i=self._sounds.length - 1; i>=0; i--) {
+        if (cnt <= limit) {
+          return;
+        }
+
+        if (self._sounds[i]._ended) {
+          // Disconnect the audio source when using Web Audio.
+          if (self._webAudio && self._sounds[i]._node) {
+            self._sounds[i]._node.disconnect(0);
+          }
+
+          // Remove sounds until we have the pool size.
+          self._sounds.splice(i, 1);
+          cnt--;
+        }
+      }
+    },
+
+    /**
+     * Get all ID's from the sounds pool.
+     * @param  {Number} id Only return one ID if one is passed.
+     * @return {Array}    Array of IDs.
+     */
+    _getSoundIds: function(id) {
+      var self = this;
+
+      if (typeof id === 'undefined') {
+        var ids = [];
+        for (var i=0; i<self._sounds.length; i++) {
+          ids.push(self._sounds[i]._id);
+        }
+
+        return ids;
+      } else {
+        return [id];
+      }
+    },
+
+    /**
+     * Load the sound back into the buffer source.
+     * @param  {Sound} sound The sound object to work with.
+     * @return {Howl}
+     */
+    _refreshBuffer: function(sound) {
+      var self = this;
+
+      // Setup the buffer source for playback.
+      sound._node.bufferSource = Howler.ctx.createBufferSource();
+      sound._node.bufferSource.buffer = cache[self._src];
+
+      // Connect to the correct node.
+      if (sound._panner) {
+        sound._node.bufferSource.connect(sound._panner);
+      } else {
+        sound._node.bufferSource.connect(sound._node);
+      }
+
+      // Setup looping and playback rate.
+      sound._node.bufferSource.loop = sound._loop;
+      if (sound._loop) {
+        sound._node.bufferSource.loopStart = sound._start || 0;
+        sound._node.bufferSource.loopEnd = sound._stop || 0;
+      }
+      sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime);
+
+      return self;
+    },
+
+    /**
+     * Prevent memory leaks by cleaning up the buffer source after playback.
+     * @param  {Object} node Sound's audio node containing the buffer source.
+     * @return {Howl}
+     */
+    _cleanBuffer: function(node) {
+      var self = this;
+      var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0;
+
+      if (Howler._scratchBuffer && node.bufferSource) {
+        node.bufferSource.onended = null;
+        node.bufferSource.disconnect(0);
+        if (isIOS) {
+          try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {}
+        }
+      }
+      node.bufferSource = null;
+
+      return self;
+    },
+
+    /**
+     * Set the source to a 0-second silence to stop any downloading (except in IE).
+     * @param  {Object} node Audio node to clear.
+     */
+    _clearSound: function(node) {
+      var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
+      if (!checkIE) {
+        node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
+      }
+    }
+  };
+
+  /** Single Sound Methods **/
+  /***************************************************************************/
+
+  /**
+   * Setup the sound object, which each node attached to a Howl group is contained in.
+   * @param {Object} howl The Howl parent group.
+   */
+  var Sound = function(howl) {
+    this._parent = howl;
+    this.init();
+  };
+  Sound.prototype = {
+    /**
+     * Initialize a new Sound object.
+     * @return {Sound}
+     */
+    init: function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Setup the default parameters.
+      self._muted = parent._muted;
+      self._loop = parent._loop;
+      self._volume = parent._volume;
+      self._rate = parent._rate;
+      self._seek = 0;
+      self._paused = true;
+      self._ended = true;
+      self._sprite = '__default';
+
+      // Generate a unique ID for this sound.
+      self._id = ++Howler._counter;
+
+      // Add itself to the parent's pool.
+      parent._sounds.push(self);
+
+      // Create the new node.
+      self.create();
+
+      return self;
+    },
+
+    /**
+     * Create and setup a new sound object, whether HTML5 Audio or Web Audio.
+     * @return {Sound}
+     */
+    create: function() {
+      var self = this;
+      var parent = self._parent;
+      var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume;
+
+      if (parent._webAudio) {
+        // Create the gain node for controlling volume (the source will connect to this).
+        self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
+        self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime);
+        self._node.paused = true;
+        self._node.connect(Howler.masterGain);
+      } else if (!Howler.noAudio) {
+        // Get an unlocked Audio object from the pool.
+        self._node = Howler._obtainHtml5Audio();
+
+        // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).
+        self._errorFn = self._errorListener.bind(self);
+        self._node.addEventListener('error', self._errorFn, false);
+
+        // Listen for 'canplaythrough' event to let us know the sound is ready.
+        self._loadFn = self._loadListener.bind(self);
+        self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false);
+
+        // Setup the new audio node.
+        self._node.src = parent._src;
+        self._node.preload = parent._preload === true ? 'auto' : parent._preload;
+        self._node.volume = volume * Howler.volume();
+
+        // Begin loading the source.
+        self._node.load();
+      }
+
+      return self;
+    },
+
+    /**
+     * Reset the parameters of this sound to the original state (for recycle).
+     * @return {Sound}
+     */
+    reset: function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Reset all of the parameters of this sound.
+      self._muted = parent._muted;
+      self._loop = parent._loop;
+      self._volume = parent._volume;
+      self._rate = parent._rate;
+      self._seek = 0;
+      self._rateSeek = 0;
+      self._paused = true;
+      self._ended = true;
+      self._sprite = '__default';
+
+      // Generate a new ID so that it isn't confused with the previous sound.
+      self._id = ++Howler._counter;
+
+      return self;
+    },
+
+    /**
+     * HTML5 Audio error listener callback.
+     */
+    _errorListener: function() {
+      var self = this;
+
+      // Fire an error event and pass back the code.
+      self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0);
+
+      // Clear the event listener.
+      self._node.removeEventListener('error', self._errorFn, false);
+    },
+
+    /**
+     * HTML5 Audio canplaythrough listener callback.
+     */
+    _loadListener: function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Round up the duration to account for the lower precision in HTML5 Audio.
+      parent._duration = Math.ceil(self._node.duration * 10) / 10;
+
+      // Setup a sprite if none is defined.
+      if (Object.keys(parent._sprite).length === 0) {
+        parent._sprite = {__default: [0, parent._duration * 1000]};
+      }
+
+      if (parent._state !== 'loaded') {
+        parent._state = 'loaded';
+        parent._emit('load');
+        parent._loadQueue();
+      }
+
+      // Clear the event listener.
+      self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
+    }
+  };
+
+  /** Helper Methods **/
+  /***************************************************************************/
+
+  var cache = {};
+
+  /**
+   * Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
+   * @param  {Howl} self
+   */
+  var loadBuffer = function(self) {
+    var url = self._src;
+
+    // Check if the buffer has already been cached and use it instead.
+    if (cache[url]) {
+      // Set the duration from the cache.
+      self._duration = cache[url].duration;
+
+      // Load the sound into this Howl.
+      loadSound(self);
+
+      return;
+    }
+
+    if (/^data:[^;]+;base64,/.test(url)) {
+      // Decode the base64 data URI without XHR, since some browsers don't support it.
+      var data = atob(url.split(',')[1]);
+      var dataView = new Uint8Array(data.length);
+      for (var i=0; i<data.length; ++i) {
+        dataView[i] = data.charCodeAt(i);
+      }
+
+      decodeAudioData(dataView.buffer, self);
+    } else {
+      // Load the buffer from the URL.
+      var xhr = new XMLHttpRequest();
+      xhr.open(self._xhr.method, url, true);
+      xhr.withCredentials = self._xhr.withCredentials;
+      xhr.responseType = 'arraybuffer';
+
+      // Apply any custom headers to the request.
+      if (self._xhr.headers) {
+        Object.keys(self._xhr.headers).forEach(function(key) {
+          xhr.setRequestHeader(key, self._xhr.headers[key]);
+        });
+      }
+
+      xhr.onload = function() {
+        // Make sure we get a successful response back.
+        var code = (xhr.status + '')[0];
+        if (code !== '0' && code !== '2' && code !== '3') {
+          self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
+          return;
+        }
+
+        decodeAudioData(xhr.response, self);
+      };
+      xhr.onerror = function() {
+        // If there is an error, switch to HTML5 Audio.
+        if (self._webAudio) {
+          self._html5 = true;
+          self._webAudio = false;
+          self._sounds = [];
+          delete cache[url];
+          self.load();
+        }
+      };
+      safeXhrSend(xhr);
+    }
+  };
+
+  /**
+   * Send the XHR request wrapped in a try/catch.
+   * @param  {Object} xhr XHR to send.
+   */
+  var safeXhrSend = function(xhr) {
+    try {
+      xhr.send();
+    } catch (e) {
+      xhr.onerror();
+    }
+  };
+
+  /**
+   * Decode audio data from an array buffer.
+   * @param  {ArrayBuffer} arraybuffer The audio data.
+   * @param  {Howl}        self
+   */
+  var decodeAudioData = function(arraybuffer, self) {
+    // Fire a load error if something broke.
+    var error = function() {
+      self._emit('loaderror', null, 'Decoding audio data failed.');
+    };
+
+    // Load the sound on success.
+    var success = function(buffer) {
+      if (buffer && self._sounds.length > 0) {
+        cache[self._src] = buffer;
+        loadSound(self, buffer);
+      } else {
+        error();
+      }
+    };
+
+    // Decode the buffer into an audio source.
+    if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
+      Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
+    } else {
+      Howler.ctx.decodeAudioData(arraybuffer, success, error);
+    }
+  }
+
+  /**
+   * Sound is now loaded, so finish setting everything up and fire the loaded event.
+   * @param  {Howl} self
+   * @param  {Object} buffer The decoded buffer sound source.
+   */
+  var loadSound = function(self, buffer) {
+    // Set the duration.
+    if (buffer && !self._duration) {
+      self._duration = buffer.duration;
+    }
+
+    // Setup a sprite if none is defined.
+    if (Object.keys(self._sprite).length === 0) {
+      self._sprite = {__default: [0, self._duration * 1000]};
+    }
+
+    // Fire the loaded event.
+    if (self._state !== 'loaded') {
+      self._state = 'loaded';
+      self._emit('load');
+      self._loadQueue();
+    }
+  };
+
+  /**
+   * Setup the audio context when available, or switch to HTML5 Audio mode.
+   */
+  var setupAudioContext = function() {
+    // If we have already detected that Web Audio isn't supported, don't run this step again.
+    if (!Howler.usingWebAudio) {
+      return;
+    }
+
+    // Check if we are using Web Audio and setup the AudioContext if we are.
+    try {
+      if (typeof AudioContext !== 'undefined') {
+        Howler.ctx = new AudioContext();
+      } else if (typeof webkitAudioContext !== 'undefined') {
+        Howler.ctx = new webkitAudioContext();
+      } else {
+        Howler.usingWebAudio = false;
+      }
+    } catch(e) {
+      Howler.usingWebAudio = false;
+    }
+
+    // If the audio context creation still failed, set using web audio to false.
+    if (!Howler.ctx) {
+      Howler.usingWebAudio = false;
+    }
+
+    // Check if a webview is being used on iOS8 or earlier (rather than the browser).
+    // If it is, disable Web Audio as it causes crashing.
+    var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
+    var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
+    var version = appVersion ? parseInt(appVersion[1], 10) : null;
+    if (iOS && version && version < 9) {
+      var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
+      if (Howler._navigator && !safari) {
+        Howler.usingWebAudio = false;
+      }
+    }
+
+    // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
+    if (Howler.usingWebAudio) {
+      Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
+      Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
+      Howler.masterGain.connect(Howler.ctx.destination);
+    }
+
+    // Re-run the setup on Howler.
+    Howler._setup();
+  };
+
+  // Add support for AMD (Asynchronous Module Definition) libraries such as require.js.
+  if (typeof define === 'function' && define.amd) {
+    define([], function() {
+      return {
+        Howler: Howler,
+        Howl: Howl
+      };
+    });
+  }
+
+  // Add support for CommonJS libraries such as browserify.
+  if (typeof exports !== 'undefined') {
+    exports.Howler = Howler;
+    exports.Howl = Howl;
+  }
+
+  // Add to global in Node.js (for testing, etc).
+  if (typeof global !== 'undefined') {
+    global.HowlerGlobal = HowlerGlobal;
+    global.Howler = Howler;
+    global.Howl = Howl;
+    global.Sound = Sound;
+  } else if (typeof window !== 'undefined') {  // Define globally in case AMD is not available or unused.
+    window.HowlerGlobal = HowlerGlobal;
+    window.Howler = Howler;
+    window.Howl = Howl;
+    window.Sound = Sound;
+  }
+})();
+
+
+/*!
+ *  Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported.
+ *  
+ *  howler.js v2.2.0
+ *  howlerjs.com
+ *
+ *  (c) 2013-2020, James Simpson of GoldFire Studios
+ *  goldfirestudios.com
+ *
+ *  MIT License
+ */
+
+(function() {
+
+  'use strict';
+
+  // Setup default properties.
+  HowlerGlobal.prototype._pos = [0, 0, 0];
+  HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0];
+
+  /** Global Methods **/
+  /***************************************************************************/
+
+  /**
+   * Helper method to update the stereo panning position of all current Howls.
+   * Future Howls will not use this value unless explicitly set.
+   * @param  {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
+   * @return {Howler/Number}     Self or current stereo panning value.
+   */
+  HowlerGlobal.prototype.stereo = function(pan) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self.ctx || !self.ctx.listener) {
+      return self;
+    }
+
+    // Loop through all Howls and update their stereo panning.
+    for (var i=self._howls.length-1; i>=0; i--) {
+      self._howls[i].stereo(pan);
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the position of the listener in 3D cartesian space. Sounds using
+   * 3D position will be relative to the listener's position.
+   * @param  {Number} x The x-position of the listener.
+   * @param  {Number} y The y-position of the listener.
+   * @param  {Number} z The z-position of the listener.
+   * @return {Howler/Array}   Self or current listener position.
+   */
+  HowlerGlobal.prototype.pos = function(x, y, z) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self.ctx || !self.ctx.listener) {
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    y = (typeof y !== 'number') ? self._pos[1] : y;
+    z = (typeof z !== 'number') ? self._pos[2] : z;
+
+    if (typeof x === 'number') {
+      self._pos = [x, y, z];
+
+      if (typeof self.ctx.listener.positionX !== 'undefined') {
+        self.ctx.listener.positionX.setTargetAtTime(self._pos[0], Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.positionY.setTargetAtTime(self._pos[1], Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.positionZ.setTargetAtTime(self._pos[2], Howler.ctx.currentTime, 0.1);
+      } else {
+        self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]);
+      }
+    } else {
+      return self._pos;
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the direction the listener is pointing in the 3D cartesian space.
+   * A front and up vector must be provided. The front is the direction the
+   * face of the listener is pointing, and up is the direction the top of the
+   * listener is pointing. Thus, these values are expected to be at right angles
+   * from each other.
+   * @param  {Number} x   The x-orientation of the listener.
+   * @param  {Number} y   The y-orientation of the listener.
+   * @param  {Number} z   The z-orientation of the listener.
+   * @param  {Number} xUp The x-orientation of the top of the listener.
+   * @param  {Number} yUp The y-orientation of the top of the listener.
+   * @param  {Number} zUp The z-orientation of the top of the listener.
+   * @return {Howler/Array}     Returns self or the current orientation vectors.
+   */
+  HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self.ctx || !self.ctx.listener) {
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    var or = self._orientation;
+    y = (typeof y !== 'number') ? or[1] : y;
+    z = (typeof z !== 'number') ? or[2] : z;
+    xUp = (typeof xUp !== 'number') ? or[3] : xUp;
+    yUp = (typeof yUp !== 'number') ? or[4] : yUp;
+    zUp = (typeof zUp !== 'number') ? or[5] : zUp;
+
+    if (typeof x === 'number') {
+      self._orientation = [x, y, z, xUp, yUp, zUp];
+
+      if (typeof self.ctx.listener.forwardX !== 'undefined') {
+        self.ctx.listener.forwardX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.forwardY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.forwardZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.upX.setTargetAtTime(xUp, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.upY.setTargetAtTime(yUp, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.upZ.setTargetAtTime(zUp, Howler.ctx.currentTime, 0.1);
+      } else {
+        self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp);
+      }
+    } else {
+      return or;
+    }
+
+    return self;
+  };
+
+  /** Group Methods **/
+  /***************************************************************************/
+
+  /**
+   * Add new properties to the core init.
+   * @param  {Function} _super Core init method.
+   * @return {Howl}
+   */
+  Howl.prototype.init = (function(_super) {
+    return function(o) {
+      var self = this;
+
+      // Setup user-defined default properties.
+      self._orientation = o.orientation || [1, 0, 0];
+      self._stereo = o.stereo || null;
+      self._pos = o.pos || null;
+      self._pannerAttr = {
+        coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360,
+        coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360,
+        coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0,
+        distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse',
+        maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000,
+        panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF',
+        refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1,
+        rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1
+      };
+
+      // Setup event listeners.
+      self._onstereo = o.onstereo ? [{fn: o.onstereo}] : [];
+      self._onpos = o.onpos ? [{fn: o.onpos}] : [];
+      self._onorientation = o.onorientation ? [{fn: o.onorientation}] : [];
+
+      // Complete initilization with howler.js core's init function.
+      return _super.call(this, o);
+    };
+  })(Howl.prototype.init);
+
+  /**
+   * Get/set the stereo panning of the audio source for this sound or all in the group.
+   * @param  {Number} pan  A value of -1.0 is all the way left and 1.0 is all the way right.
+   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
+   * @return {Howl/Number}    Returns self or the current stereo panning value.
+   */
+  Howl.prototype.stereo = function(pan, id) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable.
+    if (self._state !== 'loaded') {
+      self._queue.push({
+        event: 'stereo',
+        action: function() {
+          self.stereo(pan, id);
+        }
+      });
+
+      return self;
+    }
+
+    // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist.
+    var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo';
+
+    // Setup the group's stereo panning if no ID is passed.
+    if (typeof id === 'undefined') {
+      // Return the group's stereo panning if no parameters are passed.
+      if (typeof pan === 'number') {
+        self._stereo = pan;
+        self._pos = [pan, 0, 0];
+      } else {
+        return self._stereo;
+      }
+    }
+
+    // Change the streo panning of one or all sounds in group.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      // Get the sound.
+      var sound = self._soundById(ids[i]);
+
+      if (sound) {
+        if (typeof pan === 'number') {
+          sound._stereo = pan;
+          sound._pos = [pan, 0, 0];
+
+          if (sound._node) {
+            // If we are falling back, make sure the panningModel is equalpower.
+            sound._pannerAttr.panningModel = 'equalpower';
+
+            // Check if there is a panner setup and create a new one if not.
+            if (!sound._panner || !sound._panner.pan) {
+              setupPanner(sound, pannerType);
+            }
+
+            if (pannerType === 'spatial') {
+              if (typeof sound._panner.positionX !== 'undefined') {
+                sound._panner.positionX.setValueAtTime(pan, Howler.ctx.currentTime);
+                sound._panner.positionY.setValueAtTime(0, Howler.ctx.currentTime);
+                sound._panner.positionZ.setValueAtTime(0, Howler.ctx.currentTime);
+              } else {
+                sound._panner.setPosition(pan, 0, 0);
+              }
+            } else {
+              sound._panner.pan.setValueAtTime(pan, Howler.ctx.currentTime);
+            }
+          }
+
+          self._emit('stereo', sound._id);
+        } else {
+          return sound._stereo;
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the 3D spatial position of the audio source for this sound or group relative to the global listener.
+   * @param  {Number} x  The x-position of the audio source.
+   * @param  {Number} y  The y-position of the audio source.
+   * @param  {Number} z  The z-position of the audio source.
+   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
+   * @return {Howl/Array}    Returns self or the current 3D spatial position: [x, y, z].
+   */
+  Howl.prototype.pos = function(x, y, z, id) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // If the sound hasn't loaded, add it to the load queue to change position when capable.
+    if (self._state !== 'loaded') {
+      self._queue.push({
+        event: 'pos',
+        action: function() {
+          self.pos(x, y, z, id);
+        }
+      });
+
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    y = (typeof y !== 'number') ? 0 : y;
+    z = (typeof z !== 'number') ? -0.5 : z;
+
+    // Setup the group's spatial position if no ID is passed.
+    if (typeof id === 'undefined') {
+      // Return the group's spatial position if no parameters are passed.
+      if (typeof x === 'number') {
+        self._pos = [x, y, z];
+      } else {
+        return self._pos;
+      }
+    }
+
+    // Change the spatial position of one or all sounds in group.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      // Get the sound.
+      var sound = self._soundById(ids[i]);
+
+      if (sound) {
+        if (typeof x === 'number') {
+          sound._pos = [x, y, z];
+
+          if (sound._node) {
+            // Check if there is a panner setup and create a new one if not.
+            if (!sound._panner || sound._panner.pan) {
+              setupPanner(sound, 'spatial');
+            }
+
+            if (typeof sound._panner.positionX !== 'undefined') {
+              sound._panner.positionX.setValueAtTime(x, Howler.ctx.currentTime);
+              sound._panner.positionY.setValueAtTime(y, Howler.ctx.currentTime);
+              sound._panner.positionZ.setValueAtTime(z, Howler.ctx.currentTime);
+            } else {
+              sound._panner.setPosition(x, y, z);
+            }
+          }
+
+          self._emit('pos', sound._id);
+        } else {
+          return sound._pos;
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the direction the audio source is pointing in the 3D cartesian coordinate
+   * space. Depending on how direction the sound is, based on the `cone` attributes,
+   * a sound pointing away from the listener can be quiet or silent.
+   * @param  {Number} x  The x-orientation of the source.
+   * @param  {Number} y  The y-orientation of the source.
+   * @param  {Number} z  The z-orientation of the source.
+   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
+   * @return {Howl/Array}    Returns self or the current 3D spatial orientation: [x, y, z].
+   */
+  Howl.prototype.orientation = function(x, y, z, id) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // If the sound hasn't loaded, add it to the load queue to change orientation when capable.
+    if (self._state !== 'loaded') {
+      self._queue.push({
+        event: 'orientation',
+        action: function() {
+          self.orientation(x, y, z, id);
+        }
+      });
+
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    y = (typeof y !== 'number') ? self._orientation[1] : y;
+    z = (typeof z !== 'number') ? self._orientation[2] : z;
+
+    // Setup the group's spatial orientation if no ID is passed.
+    if (typeof id === 'undefined') {
+      // Return the group's spatial orientation if no parameters are passed.
+      if (typeof x === 'number') {
+        self._orientation = [x, y, z];
+      } else {
+        return self._orientation;
+      }
+    }
+
+    // Change the spatial orientation of one or all sounds in group.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      // Get the sound.
+      var sound = self._soundById(ids[i]);
+
+      if (sound) {
+        if (typeof x === 'number') {
+          sound._orientation = [x, y, z];
+
+          if (sound._node) {
+            // Check if there is a panner setup and create a new one if not.
+            if (!sound._panner) {
+              // Make sure we have a position to setup the node with.
+              if (!sound._pos) {
+                sound._pos = self._pos || [0, 0, -0.5];
+              }
+
+              setupPanner(sound, 'spatial');
+            }
+
+            if (typeof sound._panner.orientationX !== 'undefined') {
+              sound._panner.orientationX.setValueAtTime(x, Howler.ctx.currentTime);
+              sound._panner.orientationY.setValueAtTime(y, Howler.ctx.currentTime);
+              sound._panner.orientationZ.setValueAtTime(z, Howler.ctx.currentTime);
+            } else {
+              sound._panner.setOrientation(x, y, z);
+            }
+          }
+
+          self._emit('orientation', sound._id);
+        } else {
+          return sound._orientation;
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the panner node's attributes for a sound or group of sounds.
+   * This method can optionall take 0, 1 or 2 arguments.
+   *   pannerAttr() -> Returns the group's values.
+   *   pannerAttr(id) -> Returns the sound id's values.
+   *   pannerAttr(o) -> Set's the values of all sounds in this Howl group.
+   *   pannerAttr(o, id) -> Set's the values of passed sound id.
+   *
+   *   Attributes:
+   *     coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
+   *                      inside of which there will be no volume reduction.
+   *     coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
+   *                      outside of which the volume will be reduced to a constant value of `coneOuterGain`.
+   *     coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the
+   *                     `coneOuterAngle`. It is a linear value in the range `[0, 1]`.
+   *     distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from
+   *                     listener. Can be `linear`, `inverse` or `exponential.
+   *     maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume
+   *                   will not be reduced any further.
+   *     refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener.
+   *                   This is simply a variable of the distance model and has a different effect depending on which model
+   *                   is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance.
+   *     rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a
+   *                     variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]`
+   *                     with `inverse` and `exponential`.
+   *     panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio.
+   *                     Can be `HRTF` or `equalpower`.
+   *
+   * @return {Howl/Object} Returns self or current panner attributes.
+   */
+  Howl.prototype.pannerAttr = function() {
+    var self = this;
+    var args = arguments;
+    var o, id, sound;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // Determine the values based on arguments.
+    if (args.length === 0) {
+      // Return the group's panner attribute values.
+      return self._pannerAttr;
+    } else if (args.length === 1) {
+      if (typeof args[0] === 'object') {
+        o = args[0];
+
+        // Set the grou's panner attribute values.
+        if (typeof id === 'undefined') {
+          if (!o.pannerAttr) {
+            o.pannerAttr = {
+              coneInnerAngle: o.coneInnerAngle,
+              coneOuterAngle: o.coneOuterAngle,
+              coneOuterGain: o.coneOuterGain,
+              distanceModel: o.distanceModel,
+              maxDistance: o.maxDistance,
+              refDistance: o.refDistance,
+              rolloffFactor: o.rolloffFactor,
+              panningModel: o.panningModel
+            };
+          }
+
+          self._pannerAttr = {
+            coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle,
+            coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle,
+            coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain,
+            distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel,
+            maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance,
+            refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance,
+            rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor,
+            panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel
+          };
+        }
+      } else {
+        // Return this sound's panner attribute values.
+        sound = self._soundById(parseInt(args[0], 10));
+        return sound ? sound._pannerAttr : self._pannerAttr;
+      }
+    } else if (args.length === 2) {
+      o = args[0];
+      id = parseInt(args[1], 10);
+    }
+
+    // Update the values of the specified sounds.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      sound = self._soundById(ids[i]);
+
+      if (sound) {
+        // Merge the new values into the sound.
+        var pa = sound._pannerAttr;
+        pa = {
+          coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : pa.coneInnerAngle,
+          coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : pa.coneOuterAngle,
+          coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : pa.coneOuterGain,
+          distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : pa.distanceModel,
+          maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : pa.maxDistance,
+          refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : pa.refDistance,
+          rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : pa.rolloffFactor,
+          panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : pa.panningModel
+        };
+
+        // Update the panner values or create a new panner if none exists.
+        var panner = sound._panner;
+        if (panner) {
+          panner.coneInnerAngle = pa.coneInnerAngle;
+          panner.coneOuterAngle = pa.coneOuterAngle;
+          panner.coneOuterGain = pa.coneOuterGain;
+          panner.distanceModel = pa.distanceModel;
+          panner.maxDistance = pa.maxDistance;
+          panner.refDistance = pa.refDistance;
+          panner.rolloffFactor = pa.rolloffFactor;
+          panner.panningModel = pa.panningModel;
+        } else {
+          // Make sure we have a position to setup the node with.
+          if (!sound._pos) {
+            sound._pos = self._pos || [0, 0, -0.5];
+          }
+
+          // Create a new panner node.
+          setupPanner(sound, 'spatial');
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /** Single Sound Methods **/
+  /***************************************************************************/
+
+  /**
+   * Add new properties to the core Sound init.
+   * @param  {Function} _super Core Sound init method.
+   * @return {Sound}
+   */
+  Sound.prototype.init = (function(_super) {
+    return function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Setup user-defined default properties.
+      self._orientation = parent._orientation;
+      self._stereo = parent._stereo;
+      self._pos = parent._pos;
+      self._pannerAttr = parent._pannerAttr;
+
+      // Complete initilization with howler.js core Sound's init function.
+      _super.call(this);
+
+      // If a stereo or position was specified, set it up.
+      if (self._stereo) {
+        parent.stereo(self._stereo);
+      } else if (self._pos) {
+        parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
+      }
+    };
+  })(Sound.prototype.init);
+
+  /**
+   * Override the Sound.reset method to clean up properties from the spatial plugin.
+   * @param  {Function} _super Sound reset method.
+   * @return {Sound}
+   */
+  Sound.prototype.reset = (function(_super) {
+    return function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Reset all spatial plugin properties on this sound.
+      self._orientation = parent._orientation;
+      self._stereo = parent._stereo;
+      self._pos = parent._pos;
+      self._pannerAttr = parent._pannerAttr;
+
+      // If a stereo or position was specified, set it up.
+      if (self._stereo) {
+        parent.stereo(self._stereo);
+      } else if (self._pos) {
+        parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
+      } else if (self._panner) {
+        // Disconnect the panner.
+        self._panner.disconnect(0);
+        self._panner = undefined;
+        parent._refreshBuffer(self);
+      }
+
+      // Complete resetting of the sound.
+      return _super.call(this);
+    };
+  })(Sound.prototype.reset);
+
+  /** Helper Methods **/
+  /***************************************************************************/
+
+  /**
+   * Create a new panner node and save it on the sound.
+   * @param  {Sound} sound Specific sound to setup panning on.
+   * @param {String} type Type of panner to create: 'stereo' or 'spatial'.
+   */
+  var setupPanner = function(sound, type) {
+    type = type || 'spatial';
+
+    // Create the new panner node.
+    if (type === 'spatial') {
+      sound._panner = Howler.ctx.createPanner();
+      sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
+      sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
+      sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
+      sound._panner.distanceModel = sound._pannerAttr.distanceModel;
+      sound._panner.maxDistance = sound._pannerAttr.maxDistance;
+      sound._panner.refDistance = sound._pannerAttr.refDistance;
+      sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
+      sound._panner.panningModel = sound._pannerAttr.panningModel;
+
+      if (typeof sound._panner.positionX !== 'undefined') {
+        sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
+        sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
+        sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
+      } else {
+        sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
+      }
+
+      if (typeof sound._panner.orientationX !== 'undefined') {
+        sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
+        sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
+        sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
+      } else {
+        sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
+      }
+    } else {
+      sound._panner = Howler.ctx.createStereoPanner();
+      sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
+    }
+
+    sound._panner.connect(sound._node);
+
+    // Update the connections.
+    if (!sound._paused) {
+      sound._parent.pause(sound._id, true).play(sound._id, true);
+    }
+  };
+})();

Diff do ficheiro suprimidas por serem muito extensas
+ 1 - 0
howler/howler.min.js


Diff do ficheiro suprimidas por serem muito extensas
+ 1 - 0
howler/howler.spatial.min.js


+ 17 - 0
ios/Runner/GeneratedPluginRegistrant.h

@@ -0,0 +1,17 @@
+//
+//  Generated file. Do not edit.
+//
+
+#ifndef GeneratedPluginRegistrant_h
+#define GeneratedPluginRegistrant_h
+
+#import <Flutter/Flutter.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface GeneratedPluginRegistrant : NSObject
++ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry;
+@end
+
+NS_ASSUME_NONNULL_END
+#endif /* GeneratedPluginRegistrant_h */

+ 12 - 0
ios/Runner/GeneratedPluginRegistrant.m

@@ -0,0 +1,12 @@
+//
+//  Generated file. Do not edit.
+//
+
+#import "GeneratedPluginRegistrant.h"
+
+@implementation GeneratedPluginRegistrant
+
++ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
+}
+
+@end

+ 20 - 0
ios/flutter_sound_web.podspec

@@ -0,0 +1,20 @@
+#
+# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
+#
+Pod::Spec.new do |s|
+  s.name             = 'flutter_sound_web'
+  s.version          = '9.2.13'
+  s.summary          = 'No-op implementation of flutter_sound_web web plugin to avoid build issues on iOS'
+  s.description      = <<-DESC
+temp fake flutter_sound_web plugin
+                       DESC
+                       s.homepage         = s.homepage         = 'https://github.com/canardoux/flutter_sound/flutter_sound_web'
+  s.license          = { :file => '../LICENSE' }
+  s.author           = { 'Larpoux' => 'larpoux@gmail.com' }
+  s.source           = { :path => '.' }
+  s.source_files = 'Classes/**/*'
+  s.public_header_files = 'Classes/**/*.h'
+  s.dependency 'Flutter'
+
+  s.ios.deployment_target = '10.0'
+end

+ 159 - 0
js/flutter_sound/flutter_sound.js

@@ -0,0 +1,159 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+const VERSION = '8.2.0'
+
+
+const VERBOSE = 0;
+const DBG = 1;
+const INFO = 2;
+const WARNING = 3;
+const ERROR = 4;
+const WTF = 5;
+const NOTHING = 6;
+
+
+
+
+const codec =
+                {
+                        defaultCodec:   'defaultCodec',
+                        aacADTS:        'aacADTS',
+                        opusOGG:        'opusOGG',
+                        opusCAF:        'opusCAF',
+                        mp3:            'mp3',
+                        vorbisOGG:      'vorbisOGG',
+                        pcm16:          'pcm16',
+                        pcm16WAV:       'pcm16WAV',
+                        pcm16AIFF:      'pcm16AIFF',
+                        pcm16CAF:       'pcm16CAF',
+                        flac:           'flac',
+                        aacMP4:         'aacMP4',
+                        amrNB:          'amrNB',
+                        amrWB:          'amrWB',
+                        pcm8:           'pcm8',
+                        pcmFloat32:     'pcmFloat32',
+                        pcmWebM:        'pcmWebM',
+                        opusWebM:       'opusWebM',
+                        vorbisWebM:     'vorbisWebM',
+                };
+
+
+const tabCodec =
+                [
+                        codec.opusWebM, // codec.defaultCodec,
+                        codec.aacADTS,
+                        codec.opusOGG,
+                        codec.opusCAF,
+                        codec.mp3,
+                        codec.vorbisOGG,
+                        codec.pcm16,
+                        codec.pcm16WAV,
+                        codec.pcm16AIFF,
+                        codec.pcm16CAF,
+                        codec.flac,
+                        codec.aacMP4,
+                        codec.amrNB,
+                        codec.amrWB,
+                        codec.pcm8,
+                        codec.pcmFloat32,
+                        codec.pcmWebM,
+                        codec.opusWebM,
+                        codec.vorbisWebM,
+                ];
+
+const mime_types =
+                [
+                        'audio/webm\;codecs=opus', // defaultCodec,
+                        'audio/aac', // aacADTS,
+                        'audio/opus\;codecs=opus', // opusOGG,
+                        'audio/x-caf', // opusCAF,
+                        'audio/mp3', // mp3,
+                        'audio/ogg\;codecs=vorbis', // vorbisOGG,
+                        'audio/pcm', // pcm16,
+                        'audio/wav\;codecs=1', // pcm16WAV,
+                        'audio/aiff', // pcm16AIFF,
+                        'audio/x-caf', // pcm16CAF,
+                        'audio/x-flac', // flac,
+                        'audio/mp4', // aacMP4,
+                        'audio/AMR', // amrNB,
+                        'audio/AMR-WB', // amrWB,
+                        'audio/pcm', // pcm8,
+                        'audio/pcm', // pcmFloat32,
+                        'audio/webm\;codecs=pcm', // pcmWebM,
+                        'audio/webm\;codecs=opus', // opusWebM,
+                        'audio/webm\;codecs=vorbis', // vorbisWebM
+                ];
+
+const tabFormat =
+                [
+                        'opus', // defaultCodec,
+                        'aac', // aacADTS,
+                        'opus', // opusOGG,
+                        'caf', // opusCAF,
+                        'mp3', // mp3,
+                        'vorbis', // vorbisOGG,
+                        '', // pcm16,
+                        'wav', // pcm16WAV,
+                        'aiff', // pcm16AIFF,
+                        'caf', // pcm16CAF,
+                        'flac', // flac,
+                        'mp4', // aacMP4,
+                        'AMR', // amrNB,
+                        'AMR-WB', // amrWB,
+                        '', // pcm8,
+                        '', // pcmFloat32,
+                        'pcm', // pcmWebM,
+                        'opus', // opusWebM,
+                        'webm', // vorbisWebM
+
+                ];
+
+
+
+var instanceNumber = 0;
+var lastUrl = '';
+
+
+
+function getRecordURL( aPath,)
+{
+        var path ;
+        var myStorage;
+        if ((aPath == null) || (aPath == ''))
+        {
+                path = lastUrl;
+        } else
+        {
+                path =  aPath;
+
+        }
+        if (path.substring(0,1) == '/')
+        {
+                myStorage = window.localStorage;
+        } else
+        {
+                myStorage = window.sessionStorage;
+        }
+
+        var url = myStorage.getItem(path);
+        return url;
+}
+
+
+

+ 411 - 0
js/flutter_sound/flutter_sound_player.js

@@ -0,0 +1,411 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+
+const PLAYER_VERSION = '8.2.0'
+
+function newPlayerInstance(aCallback, callbackTable) { return new FlutterSoundPlayer(aCallback, callbackTable); }
+
+const IS_PLAYER_STOPPED = 0;
+const IS_PLAYER_PLAYING = 1;
+const IS_PLAYER_PAUSED = 2;
+
+const CB_updateProgress = 0;
+const CB_updatePlaybackState = 1;
+const CB_needSomeFood = 2;
+const CB_audioPlayerFinished = 3;
+const CB_startPlayerCompleted = 4;
+const CB_pausePlayerCompleted = 5;
+const CB_resumePlayerCompleted = 6;
+const CB_stopPlayerCompleted = 7;
+const CB_openPlayerCompleted = 8;
+const CB_closePlayerCompleted = 9;
+const CB_player_log = 10;
+
+var instanceNumber = 1;
+
+class FlutterSoundPlayer {
+
+        static newInstance(aCallback, callbackTable) { return new FlutterSoundPlayer(aCallback, callbackTable); }
+
+        constructor(aCallback, callbackTable) {
+                this.callback = aCallback;
+                this.callbackTable = callbackTable;
+                this.howl = null;
+                this.temporaryBlob = null;
+                this.status = IS_PLAYER_STOPPED;
+                //this.deltaTime = 0;
+                this.subscriptionDuration = 0;
+                this.duration = 0;
+                this.instanceNo = instanceNumber;
+                this.callbackTable[CB_player_log](this.callback, DBG, 'Instance Number : ' + this.instanceNo.toString())
+                ++instanceNumber;
+        }
+
+        initializeMediaPlayer(focus, category, mode, audioFlags, device, withUI) {
+                //this.callback.openAudioSessionCompleted(true);
+                this.status = IS_PLAYER_STOPPED;
+                this.callbackTable[CB_openPlayerCompleted](this.callback, this.getPlayerState(), true);
+                return this.getPlayerState();
+        }
+
+        releaseMediaPlayer() {
+                this.status = IS_PLAYER_STOPPED;
+                this.callbackTable[CB_closePlayerCompleted](this.callback, this.getPlayerState(), true);
+                return this.getPlayerState();
+        }
+
+
+
+        playAudioFromURL(path, codec) {
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> playAudioFromURL : ' + path);
+                var me = this;
+                var howl = new Howl
+                        ({
+                                src: [path],
+                                format: tabFormat[codec],
+
+                                onload: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onload');
+					me.howl.play();
+                                },
+
+                                onplay: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onplay');
+                                        me.duration = Math.ceil(howl.duration() * 1000);
+                                        me.status = IS_PLAYER_PLAYING;
+                                        if (me.pauseResume != IS_PLAYER_PAUSED) {
+                                                me.callbackTable[CB_startPlayerCompleted](me.callback, me.getPlayerState(), true, me.duration); // Duration is unknown
+
+                                        } else {
+                                                me.callbackTable[CB_resumePlayerCompleted](me.callback, me.getPlayerState(), true);
+
+                                        }
+                                        me.startTimer();
+
+                                },
+
+                                onplayerror: function () {
+                                        me.callbackTable[CB_player_log](me.callback, ERROR, 'onplayerror');
+                                        me.stop();
+                                },
+
+                                onend: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onend');
+                                        me.stop();
+                                        me.status = IS_PLAYER_STOPPED;
+                                        me.callbackTable[CB_audioPlayerFinished](me.callback, me.getPlayerState());
+                                },
+
+                                onloaderror: function () {
+                                        me.callbackTable[CB_player_log](me.callback, ERROR, 'onloaderror');
+                                        me.stop()
+                                },
+
+                                onpause: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onpause');
+                                        me.status = IS_PLAYER_PAUSED;
+                                        me.callbackTable[CB_pausePlayerCompleted](me.callback, me.getPlayerState(), true);
+
+                                },
+
+                                onstop: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onstop');
+                                        me.status = IS_PLAYER_STOPPED;
+                                        me.howl = null;
+                                        me.callbackTable[CB_stopPlayerCompleted](me.callback, me.getPlayerState(), true);
+                                },
+
+                                onseek: function () {
+                                        //me.callbackTable[CB_player_log](me.callback, DBG, 'onseek');
+                                },
+                        });
+
+                this.howl = howl;
+                if (this.latentVolume != null && this.latentVolume >= 0)
+                        this.howl.volume(this.latentVolume);
+                if (this.latentSpeed != null && this.latentSpeed >= 0)
+                        this.howl.rate(this.latentSpeed);
+                if (this.latentSeek != null && this.latentSeek >= 0)
+                        this.seekToPlayer(this.latentSeek);
+                this.pauseResume = IS_PLAYER_PLAYING;
+                // howl.play(); // This now done in 'onload'
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- playAudioFromURL');
+                return this.getPlayerState();
+        }
+
+
+        /* ACTUALLY NOT USED
+                playAudioFromBuffer(dataBuffer) // Actually not used
+                {
+        
+                        var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+                        var source = audioCtx.createBufferSource();
+                        me.callbackTable[CB_player_log](me.callback, DBG, dataBuffer.constructor.name)
+                        audioCtx.decodeAudioData
+                        (
+                                dataBuffer, //dataBuffer.buffer,
+                                function(buffer)
+                                {
+                                        source.buffer = buffer;
+        
+                                        source.connect(audioCtx.destination);
+                                        source.loop = false;
+                                           // start the source playing
+                                        source.start();
+                                },
+                                function(e){ me.callbackTable[CB_player_log](me.callback, DBG, "Error with decoding audio data" + e.err); }
+                        );
+                        this.callback.startPlayerCompleted(777);
+                        return 0; // playAudioFromBuffer() does not support sound Duration
+        }
+        */
+
+
+
+
+        setAudioFocus(focus, category, mode, audioFlags, device,) {
+                return this.getPlayerState();
+        }
+
+
+        isDecoderSupported(codec,) {
+                return true; // TODO
+        }
+
+        setSubscriptionDuration(duration) {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'setSubscriptionDuration');
+                this.subscriptionDuration = duration;
+                if (duration > 0 && this.howl != null)
+                        this.startTimer();
+                return this.getPlayerState();
+        }
+
+
+        getRecordURL(path,) {
+                var myStorage;
+                if ((path == null) || (path == '')) {
+                        return null;
+                }
+                if (path.includes("/"))
+                        return path;
+                if (path.substring(0, 1) == '/') {
+                        myStorage = window.localStorage;
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'localStorage');
+                } else {
+                        myStorage = window.sessionStorage;
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'sessionStorage');
+                }
+
+                var url = myStorage.getItem(path);
+                return url
+
+        }
+
+        startPlayer(codec, fromDataBuffer, fromURI, numChannels, sampleRate) {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> startPlayer');
+                this.stop();
+                if (this.temporaryBlob != null) {
+                        URL.revokeObjectURL(this.temporaryBlob);
+                        this.temporaryBlob = null;
+                }
+                if (fromDataBuffer != null) {
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'startPlayer : ' + fromDataBuffer.constructor.name);
+                        var anArray = [fromDataBuffer]; // new Array(fromDataBuffer);
+                        // return this.playAudioFromBuffer(fromDataBuffer.buffer); // playAudioFromBuffer() is ctually not used
+                        var blob = new Blob(anArray, { 'type': mime_types[codec] });
+                        fromURI = URL.createObjectURL(blob);
+                        this.temporaryBlob = fromURI;
+
+                }
+                if (fromURI == null || fromURI == '') {
+                        fromURI = lastUrl;
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'Playing lastUrl : ' + lastUrl);
+                }
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'startPlayer : ' + fromURI);
+                var url = this.getRecordURL(fromURI);
+
+                if (url != null) {
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'startPlayer : ' + url.constructor.name);
+                        fromURI = url;
+                }
+                //this.deltaTime = 0;
+                this.pauseResume = IS_PLAYER_PLAYING; // Maybe too early
+                this.playAudioFromURL(url, codec);
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- startPlayer');
+                return this.getPlayerState();
+        }
+
+        feed(data,) {
+                return this.getPlayerState();
+        }
+
+        startPlayerFromTrack(progress, duration, track, canPause, canSkipForward, canSkipBackward, defaultPauseResume, removeUIWhenStopped,) {
+                return 0; // TODO
+        }
+
+        nowPlaying(progress, duration, track, canPause, canSkipForward, canSkipBackward, defaultPauseResume,) {
+                return this.getPlayerState();
+        }
+
+        stop() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> stop');
+                this.stopTimer();
+
+
+                if (this.temporaryBlob != null)
+                        URL.revokeObjectURL(this.temporaryBlob);
+                this.temporaryBlob = null;
+
+                if (this.howl != null) {
+                        this.howl.stop();
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- stop');
+                        return true;
+                }
+                else {
+                        this.status = IS_PLAYER_STOPPED; // Maybe too early ?
+                        //this.callbackTable[CB_stopPlayerCompleted](this.callback,  IS_PLAYER_STOPPED, true);
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- stop');
+                        return false;
+                }
+
+        }
+
+        stopPlayer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> stopPlayer');
+                //if (this.howl == null)
+                //this.callbackTable[CB_stopPlayerCompleted](this.callback,  IS_PLAYER_STOPPED, true);
+                if (!this.stop())
+                        this.callbackTable[CB_stopPlayerCompleted](this.callback, this.getPlayerState(), true);
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- stopPlayer');
+                return this.getPlayerState();
+        }
+
+        getPlayerState() {
+                if (this.howl == null) {
+                        this.status = IS_PLAYER_STOPPED;
+                }
+                return this.status;
+        }
+
+        pausePlayer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> pausePlayer');
+                this.stopTimer();
+
+                if (this.getPlayerState() == IS_PLAYER_PLAYING) {
+                        //this.status = IS_PLAYER_PAUSED; // Maybe too early
+                        this.howl.pause();
+                } else {
+                        this.callbackTable[CB_pausePlayerCompleted](this.callback, this.getPlayerState(), false);
+                }
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- pausePlayer');
+                return this.getPlayerState();
+        }
+
+        resumePlayer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> resumePlayer');
+                if (this.getPlayerState() == IS_PLAYER_PAUSED) {
+                        //this.status = IS_PLAYER_PLAYING; // Maybe too early
+                        this.pauseResume = IS_PLAYER_PAUSED;
+                        this.howl.play();
+                } else {
+                        this.callbackTable[CB_resumePlayerCompleted](this.callback, this.getPlayerState(), false);
+                }
+                this.startTimer();
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- resumePlayer');
+                return this.getPlayerState();
+        }
+
+        seekToPlayer(duration) {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> seekToPlayer()');
+                if (this.howl != null) {
+                        this.latentSeek = 0;
+                        this.countDownDate = new Date().getTime() - duration;
+                        //this.deltaTime = 0;
+                        this.howl.seek(duration / 1000);
+                } else
+                        this.latentSeek = duration;
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- seekToPlayer()');
+                return this.getPlayerState();
+        }
+
+        setVolume(volume) {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> setVolume()');
+                this.latentVolume = volume;
+                if (this.howl != null)
+                        this.howl.volume(volume);
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- setVolume()');
+                return this.getPlayerState();
+        }
+
+
+        setSpeed(speed) {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> setSpeed()');
+                this.latentSpeed = speed;
+                if (this.howl != null)
+                        this.howl.rate(speed);
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- setSpeed()');
+                return this.getPlayerState();
+        }
+
+        setUIProgressBar(duration, progress) {
+                return this.getPlayerState();
+        }
+
+
+        startTimer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> startTimer()');
+                this.stopTimer();
+                var me = this;
+
+                if (this.subscriptionDuration > 0) {
+                        this.countDownDate = new Date().getTime();
+                        this.timerId = setInterval
+                                (
+                                        function () {
+                                                //var now = new Date().getTime();
+                                                //var distance = now - me.countDownDate;
+                                                //distance += me.deltaTime;
+                                                var pos = Math.floor(me.howl.seek() * 1000);
+                                                if (pos > me.duration)
+                                                        pos = me.duration;
+                                                me.callbackTable[CB_updateProgress](me.callback, pos/*me.deltaTime + distance*/, me.duration);
+
+                                        },
+                                        this.subscriptionDuration
+                                );
+                }
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- startTimer()');
+        }
+
+        stopTimer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'stopTimer()');
+                if (this.timerId != null) {
+                        clearInterval(this.timerId);
+                        //var now = new Date().getTime();
+                        //var distance = now - this.countDownDate;
+                        //this.deltaTime += distance;
+                        this.timerId = null;
+                }
+        }
+
+}

+ 380 - 0
js/flutter_sound/flutter_sound_recorder.js

@@ -0,0 +1,380 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+// const RECORDER_VERSION = '8.2.1'
+const RECORDER_VERSION = '8.2.0'
+
+const IS_RECORDER_PAUSED = 1;
+const IS_RECORDER_RECORDING = 2;
+const IS_RECORDER_STOPPED = 0;
+
+function newRecorderInstance(aCallback, callbackTable) { return new FlutterSoundRecorder(aCallback, callbackTable); }
+
+
+const CB_updateRecorderProgress = 0;
+const CB_recordingData = 1;
+const CB_startRecorderCompleted = 2;
+const CB_pauseRecorderCompleted = 3;
+const CB_resumeRecorderCompleted = 4;
+const CB_stopRecorderCompleted = 5;
+const CB_openRecorderCompleted = 6;
+const CB_closeRecorderCompleted = 7;
+const CB_recorder_log = 8;
+
+class FlutterSoundRecorder {
+        static newInstance(aCallback, callbackTable) { return new FlutterSoundRecorder(aCallback, callbackTable); }
+
+        constructor(aCallback, callbackTable) {
+                this.callback = aCallback;
+                this.callbackTable = callbackTable;
+                this.subscriptionDuration = 0;
+                this.timerId = null;
+                this.deltaTime = 0;
+                this.currentRecordPath = '';
+                this.localObjects = [];
+                this.instanceNo = instanceNumber;
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'Instance Number : ' + this.instanceNo.toString())
+                ++instanceNumber;
+        }
+
+
+
+        initializeFlautoRecorder(focus, category, mode, audioFlags, device) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'initializeFlautoRecorder');
+                this.callbackTable[CB_openRecorderCompleted](this.callback, IS_RECORDER_STOPPED, true);
+
+        }
+
+
+        deleteObjects() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> deleteObjects ');
+                for (var url in this.localObjects) {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'deleteRecord : ' + url);
+                        this.deleteRecord(url);
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- deleteObjects ');
+        }
+
+
+        releaseFlautoRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> releaseFlautoRecorder');
+                this.stop();
+                this.deleteObjects();
+                this.localObjects = [];
+
+                this.callbackTable[CB_closeRecorderCompleted](this.callback, IS_RECORDER_STOPPED, true);
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- releaseFlautoRecorder');
+        }
+
+
+        setAudioFocus(focus, category, mode, audioFlags, device) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'setAudioFocus');
+        }
+
+
+        isEncoderSupported(codec) {
+                /*
+                                for (var i in mime_types)
+                                {
+                                }
+                */
+                var r = MediaRecorder.isTypeSupported(mime_types[codec]);
+                if (r)
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'mime_types[codec] encoder is supported');
+                else
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'mime_types[codec] encoder is NOT supported');
+                return r;
+        }
+
+
+        setSubscriptionDuration(duration) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'setSubscriptionDuration');
+                this.subscriptionDuration = duration;
+                if (this.mediaRecorder != null)
+                        this.startTimer();
+        }
+
+
+        _deleteRecord(aPath,) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'deleteRecord: ' + aPath);
+                if ((aPath == null) || (aPath == '')) {
+                        path = lasturl;
+                } else {
+                        var path = aPath;
+                }
+                var myStorage;
+                if (path.substring(0, 1) == '/') {
+                        myStorage = window.localStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'localStorage');
+                } else {
+                        myStorage = window.sessionStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'sessionStorage');
+                }
+                var oldUrl = myStorage.getItem(path);
+                if (oldUrl != null && oldUrl != '') {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'Deleting object  : ' + oldUrl.toString());
+                        URL.revokeObjectURL(oldUrl);
+                        return true;
+                }
+
+                return false;
+        }
+
+
+
+        deleteRecord(path) {
+                this._deleteRecord(path);
+
+                var found = this.localObjects.findIndex(element => element == path);
+                if (found != null && found >= 0) {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, "Found : " + found);
+                        this.localObjects[found] = null;
+                }
+
+        }
+
+        setRecordURL(aPath, newUrl) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'setRecordUrl: ' + aPath + ' <- ' + newUrl);
+                var path = aPath;
+                var myStorage;
+                if ((path == null) || (path == '')) {
+                        return null;
+                }
+                if (path.substring(0, 1) == '/') {
+                        myStorage = window.localStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'localStorage');
+                } else {
+                        myStorage = window.sessionStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'sessionStorage');
+                }
+                var oldUrl = myStorage.getItem(path);
+                if (oldUrl != null && oldUrl != '') {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'Deleting object ' + ' : ' + oldUrl.toString());
+                        URL.revokeObjectURL(oldUrl);
+                } else {
+
+                }
+
+                lastUrl = aPath;
+
+                myStorage.setItem(path, newUrl);
+                this.callbackTable[CB_recorder_log](this.callback, DBG, '<--- setRecordURL ( ' + path + ' ) : ' + newUrl);
+
+        }
+
+        getRecordURL(aPath,) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, '---> getRecordURL : ' + aPath);
+                var r = getRecordURL(aPath);
+                if (r == null)
+                        r = ''; // stopRecorder does not like a null
+                this.callbackTable[CB_recorder_log](this.callback, DBG, '<--- getRecordURL :' + r);
+                return r;
+        }
+
+
+        async startRecorder(path, sampleRate, numChannels, bitRate, codec, toStream, audioSource) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'startRecorder');
+                var me = this;
+                this.currentRecordPath = path;
+                var chunks = [];
+                var mediaStream;
+                mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
+                me.mediaStream = mediaStream;
+                const audioContext = new AudioContext();
+                const _audioSource = audioContext.createMediaStreamSource(mediaStream);
+                const analyser = audioContext.createAnalyser();
+                // todo: review if this values are right (set to mimic a behaviour closest to that of Android)
+                analyser.fftSize = 512;
+                analyser.minDecibels = -110;
+                analyser.maxDecibels = 0;
+                analyser.smoothingTimeConstant = 0.4;
+                _audioSource.connect(analyser);
+                const volumes = new Uint8Array(analyser.frequencyBinCount);
+
+                this.getVolumeLevel = () => {
+                        analyser.getByteFrequencyData(volumes);
+                        let volumeSum = 0;
+                        for (const volume of volumes)
+                                volumeSum += volume;
+                        return volumeSum / volumes.length;
+                }
+                var options =
+                {
+                        audioBitsPerSecond: bitRate,
+                        mimeType: mime_types[codec]
+                }
+
+                var mediaRecorder = new MediaRecorder(mediaStream, options);
+                me.mediaRecorder = mediaRecorder;
+                if (toStream) // not yet implemented !
+                        mediaRecorder.start(30); // 30 milliseconds for a chunk
+                else
+                        mediaRecorder.start();
+                me.callbackTable[CB_recorder_log](me.callback, DBG, "recorder started : " + mediaRecorder.state);
+
+
+                mediaRecorder.ondataavailable = function (e) {
+                        if (e.data) {
+                                if (toStream) // not yet implemented !
+                                {
+                                        me.callbackTable[CB_recordingData](me.callback, e.data);
+
+                                }
+                                if (path != null && path != '') {
+                                        me.callbackTable[CB_recorder_log](me.callback, DBG, 'On data available : ' + e.data.constructor.name);
+                                        chunks.push(e.data);
+                                }
+                        }
+                }
+
+                mediaRecorder.onstart = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder OnStart');
+                        me.deltaTime = 0;
+                        me.startTimer();
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<---mediaRecorder OnStart : ' + me.mediaRecorder.state);
+                        me.callbackTable[CB_startRecorderCompleted](me.callback, IS_RECORDER_RECORDING, true);
+
+                }
+
+                mediaRecorder.onerror = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, "mediaRecorder OnError : " + e.error);
+                        me.stopRecorder()
+                }
+
+                mediaRecorder.onpause = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder onpause');
+                        me.callbackTable[CB_pauseRecorderCompleted](me.callback, IS_RECORDER_PAUSED, true);
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onpause');
+                }
+
+                mediaRecorder.onresume = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder onresume');
+                        me.callbackTable[CB_resumeRecorderCompleted](me.callback, IS_RECORDER_RECORDING, true);
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onresume');
+                }
+
+                mediaRecorder.onstop = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder onstop');
+                        encoder = new WavAudioEncoder(16000, 2);
+                        encoder.encode(chunks);
+                        var blob = encoder.finish();
+                        var url = URL.createObjectURL(blob);
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, 'Instance Number : ' + me.instanceNo.toString())
+
+                        me.setRecordURL(path, url);
+
+                        var found = me.localObjects.findIndex(element => element == path);
+                        if (found != null && found >= 0) {
+                                me.callbackTable[CB_recorder_log](me.callback, DBG, "Found : " + found);
+                                me.localObjects[found] = path;
+                        } else {
+                                me.callbackTable[CB_recorder_log](me.callback, DBG, "NOT FOUND! : " + path);
+                                me.localObjects.push(path);
+                        }
+                        chunks = null;///[];
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, 'recorder stopped');
+                        me.mediaRecorder = null;
+                        me.callbackTable[CB_stopRecorderCompleted](me.callback, IS_RECORDER_STOPPED, true, me.getRecordURL(path));
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onstop');
+                }
+                //});
+        }
+
+        stop() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> stop()');
+                this.stopTimer();
+                if (this.mediaRecorder != null) {
+                        this.mediaRecorder.stop();
+                        this.mediaRecorder = null;
+                }
+                if (this.mediaStream != null) {
+                        this.mediaStream.getTracks().forEach(track => track.stop());
+                        this.mediaStream = null;
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- stop()');
+        }
+
+        stopRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> stopRecorder');
+                this.stopTimer();
+                if (this.mediaRecorder != null) {
+                        this.mediaRecorder.stop();
+                } else {
+                        this.callbackTable[CB_stopRecorderCompleted](this.callback, IS_RECORDER_STOPPED, /*false*/true, this.getRecordURL(this.currentRecordPath));
+                }
+                this.mediaRecorder = null;
+
+                if (this.mediaStream != null) {
+                        this.mediaStream.getTracks().forEach(track => track.stop());
+                        this.mediaStream = null;
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, "JS:<--- stopRecorder");
+        }
+
+
+        pauseRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'pauseRecorder');
+                this.mediaRecorder.pause();
+                this.stopTimer();
+                this.callbackTable[CB_recorder_log](this.callback, DBG, "recorder paused : " + this.mediaRecorder.state);
+
+        }
+
+
+        resumeRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'resumeRecorder');
+                this.mediaRecorder.resume();
+                this.startTimer();
+                this.callbackTable[CB_recorder_log](this.callback, DBG, "recorder resumed : " + this.mediaRecorder.state);
+        }
+
+        startTimer() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'startTimer()');
+                this.stopTimer();
+                var me = this;
+
+                if (this.subscriptionDuration > 0) {
+                        this.countDownDate = new Date().getTime();
+                        this.timerId = setInterval
+                                (
+                                        function () {
+                                                var volumeLevel = me.getVolumeLevel();
+                                                var now = new Date().getTime();
+                                                var distance = now - me.countDownDate;
+                                                me.callbackTable[CB_updateRecorderProgress](me.callback, me.deltaTime + distance, volumeLevel);
+
+                                        },
+                                        this.subscriptionDuration
+                                );
+                }
+        }
+
+        stopTimer() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> stopTimer()');
+                if (this.timerId != null) {
+                        clearInterval(this.timerId);
+                        var now = new Date().getTime();
+                        var distance = now - this.countDownDate;
+                        this.deltaTime += distance;
+                        this.timerId = null;
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- stopTimer()');
+        }
+
+}
+

Diff do ficheiro suprimidas por serem muito extensas
+ 1 - 0
js/howler/howler.core.min.js


+ 3193 - 0
js/howler/howler.js

@@ -0,0 +1,3193 @@
+/*!
+ *  howler.js v2.2.0
+ *  howlerjs.com
+ *
+ *  (c) 2013-2020, James Simpson of GoldFire Studios
+ *  goldfirestudios.com
+ *
+ *  MIT License
+ */
+
+(function() {
+
+  'use strict';
+
+  /** Global Methods **/
+  /***************************************************************************/
+
+  /**
+   * Create the global controller. All contained methods and properties apply
+   * to all sounds that are currently playing or will be in the future.
+   */
+  var HowlerGlobal = function() {
+    this.init();
+  };
+  HowlerGlobal.prototype = {
+    /**
+     * Initialize the global Howler object.
+     * @return {Howler}
+     */
+    init: function() {
+      var self = this || Howler;
+
+      // Create a global ID counter.
+      self._counter = 1000;
+
+      // Pool of unlocked HTML5 Audio objects.
+      self._html5AudioPool = [];
+      self.html5PoolSize = 10;
+
+      // Internal properties.
+      self._codecs = {};
+      self._howls = [];
+      self._muted = false;
+      self._volume = 1;
+      self._canPlayEvent = 'canplaythrough';
+      self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null;
+
+      // Public properties.
+      self.masterGain = null;
+      self.noAudio = false;
+      self.usingWebAudio = true;
+      self.autoSuspend = true;
+      self.ctx = null;
+
+      // Set to false to disable the auto audio unlocker.
+      self.autoUnlock = true;
+
+      // Setup the various state values for global tracking.
+      self._setup();
+
+      return self;
+    },
+
+    /**
+     * Get/set the global volume for all sounds.
+     * @param  {Float} vol Volume from 0.0 to 1.0.
+     * @return {Howler/Float}     Returns self or current volume.
+     */
+    volume: function(vol) {
+      var self = this || Howler;
+      vol = parseFloat(vol);
+
+      // If we don't have an AudioContext created yet, run the setup.
+      if (!self.ctx) {
+        setupAudioContext();
+      }
+
+      if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
+        self._volume = vol;
+
+        // Don't update any of the nodes if we are muted.
+        if (self._muted) {
+          return self;
+        }
+
+        // When using Web Audio, we just need to adjust the master gain.
+        if (self.usingWebAudio) {
+          self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime);
+        }
+
+        // Loop through and change volume for all HTML5 audio nodes.
+        for (var i=0; i<self._howls.length; i++) {
+          if (!self._howls[i]._webAudio) {
+            // Get all of the sounds in this Howl group.
+            var ids = self._howls[i]._getSoundIds();
+
+            // Loop through all sounds and change the volumes.
+            for (var j=0; j<ids.length; j++) {
+              var sound = self._howls[i]._soundById(ids[j]);
+
+              if (sound && sound._node) {
+                sound._node.volume = sound._volume * vol;
+              }
+            }
+          }
+        }
+
+        return self;
+      }
+
+      return self._volume;
+    },
+
+    /**
+     * Handle muting and unmuting globally.
+     * @param  {Boolean} muted Is muted or not.
+     */
+    mute: function(muted) {
+      var self = this || Howler;
+
+      // If we don't have an AudioContext created yet, run the setup.
+      if (!self.ctx) {
+        setupAudioContext();
+      }
+
+      self._muted = muted;
+
+      // With Web Audio, we just need to mute the master gain.
+      if (self.usingWebAudio) {
+        self.masterGain.gain.setValueAtTime(muted ? 0 : self._volume, Howler.ctx.currentTime);
+      }
+
+      // Loop through and mute all HTML5 Audio nodes.
+      for (var i=0; i<self._howls.length; i++) {
+        if (!self._howls[i]._webAudio) {
+          // Get all of the sounds in this Howl group.
+          var ids = self._howls[i]._getSoundIds();
+
+          // Loop through all sounds and mark the audio node as muted.
+          for (var j=0; j<ids.length; j++) {
+            var sound = self._howls[i]._soundById(ids[j]);
+
+            if (sound && sound._node) {
+              sound._node.muted = (muted) ? true : sound._muted;
+            }
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Handle stopping all sounds globally.
+     */
+    stop: function() {
+      var self = this || Howler;
+
+      // Loop through all Howls and stop them.
+      for (var i=0; i<self._howls.length; i++) {
+        self._howls[i].stop();
+      }
+
+      return self;
+    },
+
+    /**
+     * Unload and destroy all currently loaded Howl objects.
+     * @return {Howler}
+     */
+    unload: function() {
+      var self = this || Howler;
+
+      for (var i=self._howls.length-1; i>=0; i--) {
+        self._howls[i].unload();
+      }
+
+      // Create a new AudioContext to make sure it is fully reset.
+      if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') {
+        self.ctx.close();
+        self.ctx = null;
+        setupAudioContext();
+      }
+
+      return self;
+    },
+
+    /**
+     * Check for codec support of specific extension.
+     * @param  {String} ext Audio file extention.
+     * @return {Boolean}
+     */
+    codecs: function(ext) {
+      return (this || Howler)._codecs[ext.replace(/^x-/, '')];
+    },
+
+    /**
+     * Setup various state values for global tracking.
+     * @return {Howler}
+     */
+    _setup: function() {
+      var self = this || Howler;
+
+      // Keeps track of the suspend/resume state of the AudioContext.
+      self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended';
+
+      // Automatically begin the 30-second suspend process
+      self._autoSuspend();
+
+      // Check if audio is available.
+      if (!self.usingWebAudio) {
+        // No audio is available on this system if noAudio is set to true.
+        if (typeof Audio !== 'undefined') {
+          try {
+            var test = new Audio();
+
+            // Check if the canplaythrough event is available.
+            if (typeof test.oncanplaythrough === 'undefined') {
+              self._canPlayEvent = 'canplay';
+            }
+          } catch(e) {
+            self.noAudio = true;
+          }
+        } else {
+          self.noAudio = true;
+        }
+      }
+
+      // Test to make sure audio isn't disabled in Internet Explorer.
+      try {
+        var test = new Audio();
+        if (test.muted) {
+          self.noAudio = true;
+        }
+      } catch (e) {}
+
+      // Check for supported codecs.
+      if (!self.noAudio) {
+        self._setupCodecs();
+      }
+
+      return self;
+    },
+
+    /**
+     * Check for browser support for various codecs and cache the results.
+     * @return {Howler}
+     */
+    _setupCodecs: function() {
+      var self = this || Howler;
+      var audioTest = null;
+
+      // Must wrap in a try/catch because IE11 in server mode throws an error.
+      try {
+        audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
+      } catch (err) {
+        return self;
+      }
+
+      if (!audioTest || typeof audioTest.canPlayType !== 'function') {
+        return self;
+      }
+
+      var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
+
+      // Opera version <33 has mixed MP3 support, so we need to check for and block it.
+      var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g);
+      var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);
+
+      self._codecs = {
+        mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
+        mpeg: !!mpegTest,
+        opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
+        ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
+        oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
+        wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''),
+        aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
+        caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
+        m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
+        m4b: !!(audioTest.canPlayType('audio/x-m4b;') || audioTest.canPlayType('audio/m4b;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
+        mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
+        weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
+        webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
+        dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
+        flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
+      };
+
+      return self;
+    },
+
+    /**
+     * Some browsers/devices will only allow audio to be played after a user interaction.
+     * Attempt to automatically unlock audio on the first user interaction.
+     * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
+     * @return {Howler}
+     */
+    _unlockAudio: function() {
+      var self = this || Howler;
+
+      // Only run this if Web Audio is supported and it hasn't already been unlocked.
+      if (self._audioUnlocked || !self.ctx) {
+        return;
+      }
+
+      self._audioUnlocked = false;
+      self.autoUnlock = false;
+
+      // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views.
+      // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000.
+      // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate.
+      if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) {
+        self._mobileUnloaded = true;
+        self.unload();
+      }
+
+      // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per:
+      // http://stackoverflow.com/questions/24119684
+      self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050);
+
+      // Call this method on touch start to create and play a buffer,
+      // then check if the audio actually played to determine if
+      // audio has now been unlocked on iOS, Android, etc.
+      var unlock = function(e) {
+        // Create a pool of unlocked HTML5 Audio objects that can
+        // be used for playing sounds without user interaction. HTML5
+        // Audio objects must be individually unlocked, as opposed
+        // to the WebAudio API which only needs a single activation.
+        // This must occur before WebAudio setup or the source.onended
+        // event will not fire.
+        while (self._html5AudioPool.length < self.html5PoolSize) {
+          try {
+            var audioNode = new Audio();
+
+            // Mark this Audio object as unlocked to ensure it can get returned
+            // to the unlocked pool when released.
+            audioNode._unlocked = true;
+
+            // Add the audio node to the pool.
+            self._releaseHtml5Audio(audioNode);
+          } catch (e) {
+            self.noAudio = true;
+            break;
+          }
+        }
+
+        // Loop through any assigned audio nodes and unlock them.
+        for (var i=0; i<self._howls.length; i++) {
+          if (!self._howls[i]._webAudio) {
+            // Get all of the sounds in this Howl group.
+            var ids = self._howls[i]._getSoundIds();
+
+            // Loop through all sounds and unlock the audio nodes.
+            for (var j=0; j<ids.length; j++) {
+              var sound = self._howls[i]._soundById(ids[j]);
+
+              if (sound && sound._node && !sound._node._unlocked) {
+                sound._node._unlocked = true;
+                sound._node.load();
+              }
+            }
+          }
+        }
+
+        // Fix Android can not play in suspend state.
+        self._autoResume();
+
+        // Create an empty buffer.
+        var source = self.ctx.createBufferSource();
+        source.buffer = self._scratchBuffer;
+        source.connect(self.ctx.destination);
+
+        // Play the empty buffer.
+        if (typeof source.start === 'undefined') {
+          source.noteOn(0);
+        } else {
+          source.start(0);
+        }
+
+        // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
+        if (typeof self.ctx.resume === 'function') {
+          self.ctx.resume();
+        }
+
+        // Setup a timeout to check that we are unlocked on the next event loop.
+        source.onended = function() {
+          source.disconnect(0);
+
+          // Update the unlocked state and prevent this check from happening again.
+          self._audioUnlocked = true;
+
+          // Remove the touch start listener.
+          document.removeEventListener('touchstart', unlock, true);
+          document.removeEventListener('touchend', unlock, true);
+          document.removeEventListener('click', unlock, true);
+
+          // Let all sounds know that audio has been unlocked.
+          for (var i=0; i<self._howls.length; i++) {
+            self._howls[i]._emit('unlock');
+          }
+        };
+      };
+
+      // Setup a touch start listener to attempt an unlock in.
+      document.addEventListener('touchstart', unlock, true);
+      document.addEventListener('touchend', unlock, true);
+      document.addEventListener('click', unlock, true);
+
+      return self;
+    },
+
+    /**
+     * Get an unlocked HTML5 Audio object from the pool. If none are left,
+     * return a new Audio object and throw a warning.
+     * @return {Audio} HTML5 Audio object.
+     */
+    _obtainHtml5Audio: function() {
+      var self = this || Howler;
+
+      // Return the next object from the pool if one exists.
+      if (self._html5AudioPool.length) {
+        return self._html5AudioPool.pop();
+      }
+
+      //.Check if the audio is locked and throw a warning.
+      var testPlay = new Audio().play();
+      if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) {
+        testPlay.catch(function() {
+          console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.');
+        });
+      }
+
+      return new Audio();
+    },
+
+    /**
+     * Return an activated HTML5 Audio object to the pool.
+     * @return {Howler}
+     */
+    _releaseHtml5Audio: function(audio) {
+      var self = this || Howler;
+
+      // Don't add audio to the pool if we don't know if it has been unlocked.
+      if (audio._unlocked) {
+        self._html5AudioPool.push(audio);
+      }
+
+      return self;
+    },
+
+    /**
+     * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
+     * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
+     * @return {Howler}
+     */
+    _autoSuspend: function() {
+      var self = this;
+
+      if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) {
+        return;
+      }
+
+      // Check if any sounds are playing.
+      for (var i=0; i<self._howls.length; i++) {
+        if (self._howls[i]._webAudio) {
+          for (var j=0; j<self._howls[i]._sounds.length; j++) {
+            if (!self._howls[i]._sounds[j]._paused) {
+              return self;
+            }
+          }
+        }
+      }
+
+      if (self._suspendTimer) {
+        clearTimeout(self._suspendTimer);
+      }
+
+      // If no sound has played after 30 seconds, suspend the context.
+      self._suspendTimer = setTimeout(function() {
+        if (!self.autoSuspend) {
+          return;
+        }
+
+        self._suspendTimer = null;
+        self.state = 'suspending';
+
+        // Handle updating the state of the audio context after suspending.
+        var handleSuspension = function() {
+          self.state = 'suspended';
+
+          if (self._resumeAfterSuspend) {
+            delete self._resumeAfterSuspend;
+            self._autoResume();
+          }
+        };
+
+        // Either the state gets suspended or it is interrupted.
+        // Either way, we need to update the state to suspended.
+        self.ctx.suspend().then(handleSuspension, handleSuspension);
+      }, 30000);
+
+      return self;
+    },
+
+    /**
+     * Automatically resume the Web Audio AudioContext when a new sound is played.
+     * @return {Howler}
+     */
+    _autoResume: function() {
+      var self = this;
+
+      if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) {
+        return;
+      }
+
+      if (self.state === 'running' && self.ctx.state !== 'interrupted' && self._suspendTimer) {
+        clearTimeout(self._suspendTimer);
+        self._suspendTimer = null;
+      } else if (self.state === 'suspended' || self.state === 'running' && self.ctx.state === 'interrupted') {
+        self.ctx.resume().then(function() {
+          self.state = 'running';
+
+          // Emit to all Howls that the audio has resumed.
+          for (var i=0; i<self._howls.length; i++) {
+            self._howls[i]._emit('resume');
+          }
+        });
+
+        if (self._suspendTimer) {
+          clearTimeout(self._suspendTimer);
+          self._suspendTimer = null;
+        }
+      } else if (self.state === 'suspending') {
+        self._resumeAfterSuspend = true;
+      }
+
+      return self;
+    }
+  };
+
+  // Setup the global audio controller.
+  var Howler = new HowlerGlobal();
+
+  /** Group Methods **/
+  /***************************************************************************/
+
+  /**
+   * Create an audio group controller.
+   * @param {Object} o Passed in properties for this group.
+   */
+  var Howl = function(o) {
+    var self = this;
+
+    // Throw an error if no source is provided.
+    if (!o.src || o.src.length === 0) {
+      console.error('An array of source files must be passed with any new Howl.');
+      return;
+    }
+
+    self.init(o);
+  };
+  Howl.prototype = {
+    /**
+     * Initialize a new Howl group object.
+     * @param  {Object} o Passed in properties for this group.
+     * @return {Howl}
+     */
+    init: function(o) {
+      var self = this;
+
+      // If we don't have an AudioContext created yet, run the setup.
+      if (!Howler.ctx) {
+        setupAudioContext();
+      }
+
+      // Setup user-defined default properties.
+      self._autoplay = o.autoplay || false;
+      self._format = (typeof o.format !== 'string') ? o.format : [o.format];
+      self._html5 = o.html5 || false;
+      self._muted = o.mute || false;
+      self._loop = o.loop || false;
+      self._pool = o.pool || 5;
+      self._preload = (typeof o.preload === 'boolean' || o.preload === 'metadata') ? o.preload : true;
+      self._rate = o.rate || 1;
+      self._sprite = o.sprite || {};
+      self._src = (typeof o.src !== 'string') ? o.src : [o.src];
+      self._volume = o.volume !== undefined ? o.volume : 1;
+      self._xhr = {
+        method: o.xhr && o.xhr.method ? o.xhr.method : 'GET',
+        headers: o.xhr && o.xhr.headers ? o.xhr.headers : null,
+        withCredentials: o.xhr && o.xhr.withCredentials ? o.xhr.withCredentials : false,
+      };
+
+      // Setup all other default properties.
+      self._duration = 0;
+      self._state = 'unloaded';
+      self._sounds = [];
+      self._endTimers = {};
+      self._queue = [];
+      self._playLock = false;
+
+      // Setup event listeners.
+      self._onend = o.onend ? [{fn: o.onend}] : [];
+      self._onfade = o.onfade ? [{fn: o.onfade}] : [];
+      self._onload = o.onload ? [{fn: o.onload}] : [];
+      self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
+      self._onplayerror = o.onplayerror ? [{fn: o.onplayerror}] : [];
+      self._onpause = o.onpause ? [{fn: o.onpause}] : [];
+      self._onplay = o.onplay ? [{fn: o.onplay}] : [];
+      self._onstop = o.onstop ? [{fn: o.onstop}] : [];
+      self._onmute = o.onmute ? [{fn: o.onmute}] : [];
+      self._onvolume = o.onvolume ? [{fn: o.onvolume}] : [];
+      self._onrate = o.onrate ? [{fn: o.onrate}] : [];
+      self._onseek = o.onseek ? [{fn: o.onseek}] : [];
+      self._onunlock = o.onunlock ? [{fn: o.onunlock}] : [];
+      self._onresume = [];
+
+      // Web Audio or HTML5 Audio?
+      self._webAudio = Howler.usingWebAudio && !self._html5;
+
+      // Automatically try to enable audio.
+      if (typeof Howler.ctx !== 'undefined' && Howler.ctx && Howler.autoUnlock) {
+        Howler._unlockAudio();
+      }
+
+      // Keep track of this Howl group in the global controller.
+      Howler._howls.push(self);
+
+      // If they selected autoplay, add a play event to the load queue.
+      if (self._autoplay) {
+        self._queue.push({
+          event: 'play',
+          action: function() {
+            self.play();
+          }
+        });
+      }
+
+      // Load the source file unless otherwise specified.
+      if (self._preload && self._preload !== 'none') {
+        self.load();
+      }
+
+      return self;
+    },
+
+    /**
+     * Load the audio file.
+     * @return {Howler}
+     */
+    load: function() {
+      var self = this;
+      var url = null;
+
+      // If no audio is available, quit immediately.
+      if (Howler.noAudio) {
+        self._emit('loaderror', null, 'No audio support.');
+        return;
+      }
+
+      // Make sure our source is in an array.
+      if (typeof self._src === 'string') {
+        self._src = [self._src];
+      }
+
+      // Loop through the sources and pick the first one that is compatible.
+      for (var i=0; i<self._src.length; i++) {
+        var ext, str;
+
+        if (self._format && self._format[i]) {
+          // If an extension was specified, use that instead.
+          ext = self._format[i];
+        } else {
+          // Make sure the source is a string.
+          str = self._src[i];
+          if (typeof str !== 'string') {
+            self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.');
+            continue;
+          }
+
+          // Extract the file extension from the URL or base64 data URI.
+          ext = /^data:audio\/([^;,]+);/i.exec(str);
+          if (!ext) {
+            ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]);
+          }
+
+          if (ext) {
+            ext = ext[1].toLowerCase();
+          }
+        }
+
+        // Log a warning if no extension was found.
+        if (!ext) {
+          console.warn('No file extension was found. Consider using the "format" property or specify an extension.');
+        }
+
+        // Check if this extension is available.
+        if (ext && Howler.codecs(ext)) {
+          url = self._src[i];
+          break;
+        }
+      }
+
+      if (!url) {
+        self._emit('loaderror', null, 'No codec support for selected audio sources.');
+        return;
+      }
+
+      self._src = url;
+      self._state = 'loading';
+
+      // If the hosting page is HTTPS and the source isn't,
+      // drop down to HTML5 Audio to avoid Mixed Content errors.
+      if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') {
+        self._html5 = true;
+        self._webAudio = false;
+      }
+
+      // Create a new sound object and add it to the pool.
+      new Sound(self);
+
+      // Load and decode the audio data for playback.
+      if (self._webAudio) {
+        loadBuffer(self);
+      }
+
+      return self;
+    },
+
+    /**
+     * Play a sound or resume previous playback.
+     * @param  {String/Number} sprite   Sprite name for sprite playback or sound id to continue previous.
+     * @param  {Boolean} internal Internal Use: true prevents event firing.
+     * @return {Number}          Sound ID.
+     */
+    play: function(sprite, internal) {
+      var self = this;
+      var id = null;
+
+      // Determine if a sprite, sound id or nothing was passed
+      if (typeof sprite === 'number') {
+        id = sprite;
+        sprite = null;
+      } else if (typeof sprite === 'string' && self._state === 'loaded' && !self._sprite[sprite]) {
+        // If the passed sprite doesn't exist, do nothing.
+        return null;
+      } else if (typeof sprite === 'undefined') {
+        // Use the default sound sprite (plays the full audio length).
+        sprite = '__default';
+
+        // Check if there is a single paused sound that isn't ended.
+        // If there is, play that sound. If not, continue as usual.
+        if (!self._playLock) {
+          var num = 0;
+          for (var i=0; i<self._sounds.length; i++) {
+            if (self._sounds[i]._paused && !self._sounds[i]._ended) {
+              num++;
+              id = self._sounds[i]._id;
+            }
+          }
+
+          if (num === 1) {
+            sprite = null;
+          } else {
+            id = null;
+          }
+        }
+      }
+
+      // Get the selected node, or get one from the pool.
+      var sound = id ? self._soundById(id) : self._inactiveSound();
+
+      // If the sound doesn't exist, do nothing.
+      if (!sound) {
+        return null;
+      }
+
+      // Select the sprite definition.
+      if (id && !sprite) {
+        sprite = sound._sprite || '__default';
+      }
+
+      // If the sound hasn't loaded, we must wait to get the audio's duration.
+      // We also need to wait to make sure we don't run into race conditions with
+      // the order of function calls.
+      if (self._state !== 'loaded') {
+        // Set the sprite value on this sound.
+        sound._sprite = sprite;
+
+        // Mark this sound as not ended in case another sound is played before this one loads.
+        sound._ended = false;
+
+        // Add the sound to the queue to be played on load.
+        var soundId = sound._id;
+        self._queue.push({
+          event: 'play',
+          action: function() {
+            self.play(soundId);
+          }
+        });
+
+        return soundId;
+      }
+
+      // Don't play the sound if an id was passed and it is already playing.
+      if (id && !sound._paused) {
+        // Trigger the play event, in order to keep iterating through queue.
+        if (!internal) {
+          self._loadQueue('play');
+        }
+
+        return sound._id;
+      }
+
+      // Make sure the AudioContext isn't suspended, and resume it if it is.
+      if (self._webAudio) {
+        Howler._autoResume();
+      }
+
+      // Determine how long to play for and where to start playing.
+      var seek = Math.max(0, sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000);
+      var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek);
+      var timeout = (duration * 1000) / Math.abs(sound._rate);
+      var start = self._sprite[sprite][0] / 1000;
+      var stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
+      sound._sprite = sprite;
+
+      // Mark the sound as ended instantly so that this async playback
+      // doesn't get grabbed by another call to play while this one waits to start.
+      sound._ended = false;
+
+      // Update the parameters of the sound.
+      var setParams = function() {
+        sound._paused = false;
+        sound._seek = seek;
+        sound._start = start;
+        sound._stop = stop;
+        sound._loop = !!(sound._loop || self._sprite[sprite][2]);
+      };
+
+      // End the sound instantly if seek is at the end.
+      if (seek >= stop) {
+        self._ended(sound);
+        return;
+      }
+
+      // Begin the actual playback.
+      var node = sound._node;
+      if (self._webAudio) {
+        // Fire this when the sound is ready to play to begin Web Audio playback.
+        var playWebAudio = function() {
+          self._playLock = false;
+          setParams();
+          self._refreshBuffer(sound);
+
+          // Setup the playback params.
+          var vol = (sound._muted || self._muted) ? 0 : sound._volume;
+          node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
+          sound._playStart = Howler.ctx.currentTime;
+
+          // Play the sound using the supported method.
+          if (typeof node.bufferSource.start === 'undefined') {
+            sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
+          } else {
+            sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
+          }
+
+          // Start a new timer if none is present.
+          if (timeout !== Infinity) {
+            self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
+          }
+
+          if (!internal) {
+            setTimeout(function() {
+              self._emit('play', sound._id);
+              self._loadQueue();
+            }, 0);
+          }
+        };
+
+        if (Howler.state === 'running' && Howler.ctx.state !== 'interrupted') {
+          playWebAudio();
+        } else {
+          self._playLock = true;
+
+          // Wait for the audio context to resume before playing.
+          self.once('resume', playWebAudio);
+
+          // Cancel the end timer.
+          self._clearTimer(sound._id);
+        }
+      } else {
+        // Fire this when the sound is ready to play to begin HTML5 Audio playback.
+        var playHtml5 = function() {
+          node.currentTime = seek;
+          node.muted = sound._muted || self._muted || Howler._muted || node.muted;
+          node.volume = sound._volume * Howler.volume();
+          node.playbackRate = sound._rate;
+
+          // Some browsers will throw an error if this is called without user interaction.
+          try {
+            var play = node.play();
+
+            // Support older browsers that don't support promises, and thus don't have this issue.
+            if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
+              // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
+              self._playLock = true;
+
+              // Set param values immediately.
+              setParams();
+
+              // Releases the lock and executes queued actions.
+              play
+                .then(function() {
+                  self._playLock = false;
+                  node._unlocked = true;
+                  if (!internal) {
+                    self._emit('play', sound._id);
+                    self._loadQueue();
+                  }
+                })
+                .catch(function() {
+                  self._playLock = false;
+                  self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
+                    'on mobile devices and Chrome where playback was not within a user interaction.');
+
+                  // Reset the ended and paused values.
+                  sound._ended = true;
+                  sound._paused = true;
+                });
+            } else if (!internal) {
+              self._playLock = false;
+              setParams();
+              self._emit('play', sound._id);
+              self._loadQueue();
+            }
+
+            // Setting rate before playing won't work in IE, so we set it again here.
+            node.playbackRate = sound._rate;
+
+            // If the node is still paused, then we can assume there was a playback issue.
+            if (node.paused) {
+              self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
+                'on mobile devices and Chrome where playback was not within a user interaction.');
+              return;
+            }
+
+            // Setup the end timer on sprites or listen for the ended event.
+            if (sprite !== '__default' || sound._loop) {
+              self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
+            } else {
+              self._endTimers[sound._id] = function() {
+                // Fire ended on this audio node.
+                self._ended(sound);
+
+                // Clear this listener.
+                node.removeEventListener('ended', self._endTimers[sound._id], false);
+              };
+              node.addEventListener('ended', self._endTimers[sound._id], false);
+            }
+          } catch (err) {
+            self._emit('playerror', sound._id, err);
+          }
+        };
+
+        // If this is streaming audio, make sure the src is set and load again.
+        if (node.src === 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA') {
+          node.src = self._src;
+          node.load();
+        }
+
+        // Play immediately if ready, or wait for the 'canplaythrough'e vent.
+        var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS);
+        if (node.readyState >= 3 || loadedNoReadyState) {
+          playHtml5();
+        } else {
+          self._playLock = true;
+
+          var listener = function() {
+            // Begin playback.
+            playHtml5();
+
+            // Clear this listener.
+            node.removeEventListener(Howler._canPlayEvent, listener, false);
+          };
+          node.addEventListener(Howler._canPlayEvent, listener, false);
+
+          // Cancel the end timer.
+          self._clearTimer(sound._id);
+        }
+      }
+
+      return sound._id;
+    },
+
+    /**
+     * Pause playback and save current position.
+     * @param  {Number} id The sound ID (empty to pause all in group).
+     * @return {Howl}
+     */
+    pause: function(id) {
+      var self = this;
+
+      // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'pause',
+          action: function() {
+            self.pause(id);
+          }
+        });
+
+        return self;
+      }
+
+      // If no id is passed, get all ID's to be paused.
+      var ids = self._getSoundIds(id);
+
+      for (var i=0; i<ids.length; i++) {
+        // Clear the end timer.
+        self._clearTimer(ids[i]);
+
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        if (sound && !sound._paused) {
+          // Reset the seek position.
+          sound._seek = self.seek(ids[i]);
+          sound._rateSeek = 0;
+          sound._paused = true;
+
+          // Stop currently running fades.
+          self._stopFade(ids[i]);
+
+          if (sound._node) {
+            if (self._webAudio) {
+              // Make sure the sound has been created.
+              if (!sound._node.bufferSource) {
+                continue;
+              }
+
+              if (typeof sound._node.bufferSource.stop === 'undefined') {
+                sound._node.bufferSource.noteOff(0);
+              } else {
+                sound._node.bufferSource.stop(0);
+              }
+
+              // Clean up the buffer source.
+              self._cleanBuffer(sound._node);
+            } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
+              sound._node.pause();
+            }
+          }
+        }
+
+        // Fire the pause event, unless `true` is passed as the 2nd argument.
+        if (!arguments[1]) {
+          self._emit('pause', sound ? sound._id : null);
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Stop playback and reset to start.
+     * @param  {Number} id The sound ID (empty to stop all in group).
+     * @param  {Boolean} internal Internal Use: true prevents event firing.
+     * @return {Howl}
+     */
+    stop: function(id, internal) {
+      var self = this;
+
+      // If the sound hasn't loaded, add it to the load queue to stop when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'stop',
+          action: function() {
+            self.stop(id);
+          }
+        });
+
+        return self;
+      }
+
+      // If no id is passed, get all ID's to be stopped.
+      var ids = self._getSoundIds(id);
+
+      for (var i=0; i<ids.length; i++) {
+        // Clear the end timer.
+        self._clearTimer(ids[i]);
+
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        if (sound) {
+          // Reset the seek position.
+          sound._seek = sound._start || 0;
+          sound._rateSeek = 0;
+          sound._paused = true;
+          sound._ended = true;
+
+          // Stop currently running fades.
+          self._stopFade(ids[i]);
+
+          if (sound._node) {
+            if (self._webAudio) {
+              // Make sure the sound's AudioBufferSourceNode has been created.
+              if (sound._node.bufferSource) {
+                if (typeof sound._node.bufferSource.stop === 'undefined') {
+                  sound._node.bufferSource.noteOff(0);
+                } else {
+                  sound._node.bufferSource.stop(0);
+                }
+
+                // Clean up the buffer source.
+                self._cleanBuffer(sound._node);
+              }
+            } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
+              sound._node.currentTime = sound._start || 0;
+              sound._node.pause();
+
+              // If this is a live stream, stop download once the audio is stopped.
+              if (sound._node.duration === Infinity) {
+                self._clearSound(sound._node);
+              }
+            }
+          }
+
+          if (!internal) {
+            self._emit('stop', sound._id);
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Mute/unmute a single sound or all sounds in this Howl group.
+     * @param  {Boolean} muted Set to true to mute and false to unmute.
+     * @param  {Number} id    The sound ID to update (omit to mute/unmute all).
+     * @return {Howl}
+     */
+    mute: function(muted, id) {
+      var self = this;
+
+      // If the sound hasn't loaded, add it to the load queue to mute when capable.
+      if (self._state !== 'loaded'|| self._playLock) {
+        self._queue.push({
+          event: 'mute',
+          action: function() {
+            self.mute(muted, id);
+          }
+        });
+
+        return self;
+      }
+
+      // If applying mute/unmute to all sounds, update the group's value.
+      if (typeof id === 'undefined') {
+        if (typeof muted === 'boolean') {
+          self._muted = muted;
+        } else {
+          return self._muted;
+        }
+      }
+
+      // If no id is passed, get all ID's to be muted.
+      var ids = self._getSoundIds(id);
+
+      for (var i=0; i<ids.length; i++) {
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        if (sound) {
+          sound._muted = muted;
+
+          // Cancel active fade and set the volume to the end value.
+          if (sound._interval) {
+            self._stopFade(sound._id);
+          }
+
+          if (self._webAudio && sound._node) {
+            sound._node.gain.setValueAtTime(muted ? 0 : sound._volume, Howler.ctx.currentTime);
+          } else if (sound._node) {
+            sound._node.muted = Howler._muted ? true : muted;
+          }
+
+          self._emit('mute', sound._id);
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the volume of this sound or of the Howl group. This method can optionally take 0, 1 or 2 arguments.
+     *   volume() -> Returns the group's volume value.
+     *   volume(id) -> Returns the sound id's current volume.
+     *   volume(vol) -> Sets the volume of all sounds in this Howl group.
+     *   volume(vol, id) -> Sets the volume of passed sound id.
+     * @return {Howl/Number} Returns self or current volume.
+     */
+    volume: function() {
+      var self = this;
+      var args = arguments;
+      var vol, id;
+
+      // Determine the values based on arguments.
+      if (args.length === 0) {
+        // Return the value of the groups' volume.
+        return self._volume;
+      } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') {
+        // First check if this is an ID, and if not, assume it is a new volume.
+        var ids = self._getSoundIds();
+        var index = ids.indexOf(args[0]);
+        if (index >= 0) {
+          id = parseInt(args[0], 10);
+        } else {
+          vol = parseFloat(args[0]);
+        }
+      } else if (args.length >= 2) {
+        vol = parseFloat(args[0]);
+        id = parseInt(args[1], 10);
+      }
+
+      // Update the volume or return the current volume.
+      var sound;
+      if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
+        // If the sound hasn't loaded, add it to the load queue to change volume when capable.
+        if (self._state !== 'loaded'|| self._playLock) {
+          self._queue.push({
+            event: 'volume',
+            action: function() {
+              self.volume.apply(self, args);
+            }
+          });
+
+          return self;
+        }
+
+        // Set the group volume.
+        if (typeof id === 'undefined') {
+          self._volume = vol;
+        }
+
+        // Update one or all volumes.
+        id = self._getSoundIds(id);
+        for (var i=0; i<id.length; i++) {
+          // Get the sound.
+          sound = self._soundById(id[i]);
+
+          if (sound) {
+            sound._volume = vol;
+
+            // Stop currently running fades.
+            if (!args[2]) {
+              self._stopFade(id[i]);
+            }
+
+            if (self._webAudio && sound._node && !sound._muted) {
+              sound._node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
+            } else if (sound._node && !sound._muted) {
+              sound._node.volume = vol * Howler.volume();
+            }
+
+            self._emit('volume', sound._id);
+          }
+        }
+      } else {
+        sound = id ? self._soundById(id) : self._sounds[0];
+        return sound ? sound._volume : 0;
+      }
+
+      return self;
+    },
+
+    /**
+     * Fade a currently playing sound between two volumes (if no id is passed, all sounds will fade).
+     * @param  {Number} from The value to fade from (0.0 to 1.0).
+     * @param  {Number} to   The volume to fade to (0.0 to 1.0).
+     * @param  {Number} len  Time in milliseconds to fade.
+     * @param  {Number} id   The sound id (omit to fade all sounds).
+     * @return {Howl}
+     */
+    fade: function(from, to, len, id) {
+      var self = this;
+
+      // If the sound hasn't loaded, add it to the load queue to fade when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'fade',
+          action: function() {
+            self.fade(from, to, len, id);
+          }
+        });
+
+        return self;
+      }
+
+      // Make sure the to/from/len values are numbers.
+      from = Math.min(Math.max(0, parseFloat(from)), 1);
+      to = Math.min(Math.max(0, parseFloat(to)), 1);
+      len = parseFloat(len);
+
+      // Set the volume to the start position.
+      self.volume(from, id);
+
+      // Fade the volume of one or all sounds.
+      var ids = self._getSoundIds(id);
+      for (var i=0; i<ids.length; i++) {
+        // Get the sound.
+        var sound = self._soundById(ids[i]);
+
+        // Create a linear fade or fall back to timeouts with HTML5 Audio.
+        if (sound) {
+          // Stop the previous fade if no sprite is being used (otherwise, volume handles this).
+          if (!id) {
+            self._stopFade(ids[i]);
+          }
+
+          // If we are using Web Audio, let the native methods do the actual fade.
+          if (self._webAudio && !sound._muted) {
+            var currentTime = Howler.ctx.currentTime;
+            var end = currentTime + (len / 1000);
+            sound._volume = from;
+            sound._node.gain.setValueAtTime(from, currentTime);
+            sound._node.gain.linearRampToValueAtTime(to, end);
+          }
+
+          self._startFadeInterval(sound, from, to, len, ids[i], typeof id === 'undefined');
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Starts the internal interval to fade a sound.
+     * @param  {Object} sound Reference to sound to fade.
+     * @param  {Number} from The value to fade from (0.0 to 1.0).
+     * @param  {Number} to   The volume to fade to (0.0 to 1.0).
+     * @param  {Number} len  Time in milliseconds to fade.
+     * @param  {Number} id   The sound id to fade.
+     * @param  {Boolean} isGroup   If true, set the volume on the group.
+     */
+    _startFadeInterval: function(sound, from, to, len, id, isGroup) {
+      var self = this;
+      var vol = from;
+      var diff = to - from;
+      var steps = Math.abs(diff / 0.01);
+      var stepLen = Math.max(4, (steps > 0) ? len / steps : len);
+      var lastTick = Date.now();
+
+      // Store the value being faded to.
+      sound._fadeTo = to;
+
+      // Update the volume value on each interval tick.
+      sound._interval = setInterval(function() {
+        // Update the volume based on the time since the last tick.
+        var tick = (Date.now() - lastTick) / len;
+        lastTick = Date.now();
+        vol += diff * tick;
+
+        // Make sure the volume is in the right bounds.
+        if (diff < 0) {
+          vol = Math.max(to, vol);
+        } else {
+          vol = Math.min(to, vol);
+        }
+
+        // Round to within 2 decimal points.
+        vol = Math.round(vol * 100) / 100;
+
+        // Change the volume.
+        if (self._webAudio) {
+          sound._volume = vol;
+        } else {
+          self.volume(vol, sound._id, true);
+        }
+
+        // Set the group's volume.
+        if (isGroup) {
+          self._volume = vol;
+        }
+
+        // When the fade is complete, stop it and fire event.
+        if ((to < from && vol <= to) || (to > from && vol >= to)) {
+          clearInterval(sound._interval);
+          sound._interval = null;
+          sound._fadeTo = null;
+          self.volume(to, sound._id);
+          self._emit('fade', sound._id);
+        }
+      }, stepLen);
+    },
+
+    /**
+     * Internal method that stops the currently playing fade when
+     * a new fade starts, volume is changed or the sound is stopped.
+     * @param  {Number} id The sound id.
+     * @return {Howl}
+     */
+    _stopFade: function(id) {
+      var self = this;
+      var sound = self._soundById(id);
+
+      if (sound && sound._interval) {
+        if (self._webAudio) {
+          sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime);
+        }
+
+        clearInterval(sound._interval);
+        sound._interval = null;
+        self.volume(sound._fadeTo, id);
+        sound._fadeTo = null;
+        self._emit('fade', id);
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
+     *   loop() -> Returns the group's loop value.
+     *   loop(id) -> Returns the sound id's loop value.
+     *   loop(loop) -> Sets the loop value for all sounds in this Howl group.
+     *   loop(loop, id) -> Sets the loop value of passed sound id.
+     * @return {Howl/Boolean} Returns self or current loop value.
+     */
+    loop: function() {
+      var self = this;
+      var args = arguments;
+      var loop, id, sound;
+
+      // Determine the values for loop and id.
+      if (args.length === 0) {
+        // Return the grou's loop value.
+        return self._loop;
+      } else if (args.length === 1) {
+        if (typeof args[0] === 'boolean') {
+          loop = args[0];
+          self._loop = loop;
+        } else {
+          // Return this sound's loop value.
+          sound = self._soundById(parseInt(args[0], 10));
+          return sound ? sound._loop : false;
+        }
+      } else if (args.length === 2) {
+        loop = args[0];
+        id = parseInt(args[1], 10);
+      }
+
+      // If no id is passed, get all ID's to be looped.
+      var ids = self._getSoundIds(id);
+      for (var i=0; i<ids.length; i++) {
+        sound = self._soundById(ids[i]);
+
+        if (sound) {
+          sound._loop = loop;
+          if (self._webAudio && sound._node && sound._node.bufferSource) {
+            sound._node.bufferSource.loop = loop;
+            if (loop) {
+              sound._node.bufferSource.loopStart = sound._start || 0;
+              sound._node.bufferSource.loopEnd = sound._stop;
+            }
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the playback rate of a sound. This method can optionally take 0, 1 or 2 arguments.
+     *   rate() -> Returns the first sound node's current playback rate.
+     *   rate(id) -> Returns the sound id's current playback rate.
+     *   rate(rate) -> Sets the playback rate of all sounds in this Howl group.
+     *   rate(rate, id) -> Sets the playback rate of passed sound id.
+     * @return {Howl/Number} Returns self or the current playback rate.
+     */
+    rate: function() {
+      var self = this;
+      var args = arguments;
+      var rate, id;
+
+      // Determine the values based on arguments.
+      if (args.length === 0) {
+        // We will simply return the current rate of the first node.
+        id = self._sounds[0]._id;
+      } else if (args.length === 1) {
+        // First check if this is an ID, and if not, assume it is a new rate value.
+        var ids = self._getSoundIds();
+        var index = ids.indexOf(args[0]);
+        if (index >= 0) {
+          id = parseInt(args[0], 10);
+        } else {
+          rate = parseFloat(args[0]);
+        }
+      } else if (args.length === 2) {
+        rate = parseFloat(args[0]);
+        id = parseInt(args[1], 10);
+      }
+
+      // Update the playback rate or return the current value.
+      var sound;
+      if (typeof rate === 'number') {
+        // If the sound hasn't loaded, add it to the load queue to change playback rate when capable.
+        if (self._state !== 'loaded' || self._playLock) {
+          self._queue.push({
+            event: 'rate',
+            action: function() {
+              self.rate.apply(self, args);
+            }
+          });
+
+          return self;
+        }
+
+        // Set the group rate.
+        if (typeof id === 'undefined') {
+          self._rate = rate;
+        }
+
+        // Update one or all volumes.
+        id = self._getSoundIds(id);
+        for (var i=0; i<id.length; i++) {
+          // Get the sound.
+          sound = self._soundById(id[i]);
+
+          if (sound) {
+            // Keep track of our position when the rate changed and update the playback
+            // start position so we can properly adjust the seek position for time elapsed.
+            if (self.playing(id[i])) {
+              sound._rateSeek = self.seek(id[i]);
+              sound._playStart = self._webAudio ? Howler.ctx.currentTime : sound._playStart;
+            }
+            sound._rate = rate;
+
+            // Change the playback rate.
+            if (self._webAudio && sound._node && sound._node.bufferSource) {
+              sound._node.bufferSource.playbackRate.setValueAtTime(rate, Howler.ctx.currentTime);
+            } else if (sound._node) {
+              sound._node.playbackRate = rate;
+            }
+
+            // Reset the timers.
+            var seek = self.seek(id[i]);
+            var duration = ((self._sprite[sound._sprite][0] + self._sprite[sound._sprite][1]) / 1000) - seek;
+            var timeout = (duration * 1000) / Math.abs(sound._rate);
+
+            // Start a new end timer if sound is already playing.
+            if (self._endTimers[id[i]] || !sound._paused) {
+              self._clearTimer(id[i]);
+              self._endTimers[id[i]] = setTimeout(self._ended.bind(self, sound), timeout);
+            }
+
+            self._emit('rate', sound._id);
+          }
+        }
+      } else {
+        sound = self._soundById(id);
+        return sound ? sound._rate : self._rate;
+      }
+
+      return self;
+    },
+
+    /**
+     * Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
+     *   seek() -> Returns the first sound node's current seek position.
+     *   seek(id) -> Returns the sound id's current seek position.
+     *   seek(seek) -> Sets the seek position of the first sound node.
+     *   seek(seek, id) -> Sets the seek position of passed sound id.
+     * @return {Howl/Number} Returns self or the current seek position.
+     */
+    seek: function() {
+      var self = this;
+      var args = arguments;
+      var seek, id;
+
+      // Determine the values based on arguments.
+      if (args.length === 0) {
+        // We will simply return the current position of the first node.
+        id = self._sounds[0]._id;
+      } else if (args.length === 1) {
+        // First check if this is an ID, and if not, assume it is a new seek position.
+        var ids = self._getSoundIds();
+        var index = ids.indexOf(args[0]);
+        if (index >= 0) {
+          id = parseInt(args[0], 10);
+        } else if (self._sounds.length) {
+          id = self._sounds[0]._id;
+          seek = parseFloat(args[0]);
+        }
+      } else if (args.length === 2) {
+        seek = parseFloat(args[0]);
+        id = parseInt(args[1], 10);
+      }
+
+      // If there is no ID, bail out.
+      if (typeof id === 'undefined') {
+        return self;
+      }
+
+      // If the sound hasn't loaded, add it to the load queue to seek when capable.
+      if (self._state !== 'loaded' || self._playLock) {
+        self._queue.push({
+          event: 'seek',
+          action: function() {
+            self.seek.apply(self, args);
+          }
+        });
+
+        return self;
+      }
+
+      // Get the sound.
+      var sound = self._soundById(id);
+
+      if (sound) {
+        if (typeof seek === 'number' && seek >= 0) {
+          // Pause the sound and update position for restarting playback.
+          var playing = self.playing(id);
+          if (playing) {
+            self.pause(id, true);
+          }
+
+          // Move the position of the track and cancel timer.
+          sound._seek = seek;
+          sound._ended = false;
+          self._clearTimer(id);
+
+          // Update the seek position for HTML5 Audio.
+          if (!self._webAudio && sound._node && !isNaN(sound._node.duration)) {
+            sound._node.currentTime = seek;
+          }
+
+          // Seek and emit when ready.
+          var seekAndEmit = function() {
+            self._emit('seek', id);
+
+            // Restart the playback if the sound was playing.
+            if (playing) {
+              self.play(id, true);
+            }
+          };
+
+          // Wait for the play lock to be unset before emitting (HTML5 Audio).
+          if (playing && !self._webAudio) {
+            var emitSeek = function() {
+              if (!self._playLock) {
+                seekAndEmit();
+              } else {
+                setTimeout(emitSeek, 0);
+              }
+            };
+            setTimeout(emitSeek, 0);
+          } else {
+            seekAndEmit();
+          }
+        } else {
+          if (self._webAudio) {
+            var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0;
+            var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0;
+            return sound._seek + (rateSeek + realTime * Math.abs(sound._rate));
+          } else {
+            return sound._node.currentTime;
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * 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.
+     * @param  {Number}  id The sound id to check. If none is passed, the whole sound group is checked.
+     * @return {Boolean} True if playing and false if not.
+     */
+    playing: function(id) {
+      var self = this;
+
+      // Check the passed sound ID (if any).
+      if (typeof id === 'number') {
+        var sound = self._soundById(id);
+        return sound ? !sound._paused : false;
+      }
+
+      // Otherwise, loop through all sounds and check if any are playing.
+      for (var i=0; i<self._sounds.length; i++) {
+        if (!self._sounds[i]._paused) {
+          return true;
+        }
+      }
+
+      return false;
+    },
+
+    /**
+     * Get the duration of this sound. Passing a sound id will return the sprite duration.
+     * @param  {Number} id The sound id to check. If none is passed, return full source duration.
+     * @return {Number} Audio duration in seconds.
+     */
+    duration: function(id) {
+      var self = this;
+      var duration = self._duration;
+
+      // If we pass an ID, get the sound and return the sprite length.
+      var sound = self._soundById(id);
+      if (sound) {
+        duration = self._sprite[sound._sprite][1] / 1000;
+      }
+
+      return duration;
+    },
+
+    /**
+     * Returns the current loaded state of this Howl.
+     * @return {String} 'unloaded', 'loading', 'loaded'
+     */
+    state: function() {
+      return this._state;
+    },
+
+    /**
+     * Unload and destroy the current Howl object.
+     * This will immediately stop all sound instances attached to this group.
+     */
+    unload: function() {
+      var self = this;
+
+      // Stop playing any active sounds.
+      var sounds = self._sounds;
+      for (var i=0; i<sounds.length; i++) {
+        // Stop the sound if it is currently playing.
+        if (!sounds[i]._paused) {
+          self.stop(sounds[i]._id);
+        }
+
+        // Remove the source or disconnect.
+        if (!self._webAudio) {
+          // Set the source to 0-second silence to stop any downloading (except in IE).
+          self._clearSound(sounds[i]._node);
+
+          // Remove any event listeners.
+          sounds[i]._node.removeEventListener('error', sounds[i]._errorFn, false);
+          sounds[i]._node.removeEventListener(Howler._canPlayEvent, sounds[i]._loadFn, false);
+
+          // Release the Audio object back to the pool.
+          Howler._releaseHtml5Audio(sounds[i]._node);
+        }
+
+        // Empty out all of the nodes.
+        delete sounds[i]._node;
+
+        // Make sure all timers are cleared out.
+        self._clearTimer(sounds[i]._id);
+      }
+
+      // Remove the references in the global Howler object.
+      var index = Howler._howls.indexOf(self);
+      if (index >= 0) {
+        Howler._howls.splice(index, 1);
+      }
+
+      // Delete this sound from the cache (if no other Howl is using it).
+      var remCache = true;
+      for (i=0; i<Howler._howls.length; i++) {
+        if (Howler._howls[i]._src === self._src || self._src.indexOf(Howler._howls[i]._src) >= 0) {
+          remCache = false;
+          break;
+        }
+      }
+
+      if (cache && remCache) {
+        delete cache[self._src];
+      }
+
+      // Clear global errors.
+      Howler.noAudio = false;
+
+      // Clear out `self`.
+      self._state = 'unloaded';
+      self._sounds = [];
+      self = null;
+
+      return null;
+    },
+
+    /**
+     * Listen to a custom event.
+     * @param  {String}   event Event name.
+     * @param  {Function} fn    Listener to call.
+     * @param  {Number}   id    (optional) Only listen to events for this sound.
+     * @param  {Number}   once  (INTERNAL) Marks event to fire only once.
+     * @return {Howl}
+     */
+    on: function(event, fn, id, once) {
+      var self = this;
+      var events = self['_on' + event];
+
+      if (typeof fn === 'function') {
+        events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn});
+      }
+
+      return self;
+    },
+
+    /**
+     * Remove a custom event. Call without parameters to remove all events.
+     * @param  {String}   event Event name.
+     * @param  {Function} fn    Listener to remove. Leave empty to remove all.
+     * @param  {Number}   id    (optional) Only remove events for this sound.
+     * @return {Howl}
+     */
+    off: function(event, fn, id) {
+      var self = this;
+      var events = self['_on' + event];
+      var i = 0;
+
+      // Allow passing just an event and ID.
+      if (typeof fn === 'number') {
+        id = fn;
+        fn = null;
+      }
+
+      if (fn || id) {
+        // Loop through event store and remove the passed function.
+        for (i=0; i<events.length; i++) {
+          var isId = (id === events[i].id);
+          if (fn === events[i].fn && isId || !fn && isId) {
+            events.splice(i, 1);
+            break;
+          }
+        }
+      } else if (event) {
+        // Clear out all events of this type.
+        self['_on' + event] = [];
+      } else {
+        // Clear out all events of every type.
+        var keys = Object.keys(self);
+        for (i=0; i<keys.length; i++) {
+          if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) {
+            self[keys[i]] = [];
+          }
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Listen to a custom event and remove it once fired.
+     * @param  {String}   event Event name.
+     * @param  {Function} fn    Listener to call.
+     * @param  {Number}   id    (optional) Only listen to events for this sound.
+     * @return {Howl}
+     */
+    once: function(event, fn, id) {
+      var self = this;
+
+      // Setup the event listener.
+      self.on(event, fn, id, 1);
+
+      return self;
+    },
+
+    /**
+     * Emit all events of a specific type and pass the sound id.
+     * @param  {String} event Event name.
+     * @param  {Number} id    Sound ID.
+     * @param  {Number} msg   Message to go with event.
+     * @return {Howl}
+     */
+    _emit: function(event, id, msg) {
+      var self = this;
+      var events = self['_on' + event];
+
+      // Loop through event store and fire all functions.
+      for (var i=events.length-1; i>=0; i--) {
+        // Only fire the listener if the correct ID is used.
+        if (!events[i].id || events[i].id === id || event === 'load') {
+          setTimeout(function(fn) {
+            fn.call(this, id, msg);
+          }.bind(self, events[i].fn), 0);
+
+          // If this event was setup with `once`, remove it.
+          if (events[i].once) {
+            self.off(event, events[i].fn, events[i].id);
+          }
+        }
+      }
+
+      // Pass the event type into load queue so that it can continue stepping.
+      self._loadQueue(event);
+
+      return self;
+    },
+
+    /**
+     * Queue of actions initiated before the sound has loaded.
+     * These will be called in sequence, with the next only firing
+     * after the previous has finished executing (even if async like play).
+     * @return {Howl}
+     */
+    _loadQueue: function(event) {
+      var self = this;
+
+      if (self._queue.length > 0) {
+        var task = self._queue[0];
+
+        // Remove this task if a matching event was passed.
+        if (task.event === event) {
+          self._queue.shift();
+          self._loadQueue();
+        }
+
+        // Run the task if no event type is passed.
+        if (!event) {
+          task.action();
+        }
+      }
+
+      return self;
+    },
+
+    /**
+     * Fired when playback ends at the end of the duration.
+     * @param  {Sound} sound The sound object to work with.
+     * @return {Howl}
+     */
+    _ended: function(sound) {
+      var self = this;
+      var sprite = sound._sprite;
+
+      // If we are using IE and there was network latency we may be clipping
+      // audio before it completes playing. Lets check the node to make sure it
+      // believes it has completed, before ending the playback.
+      if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) {
+        setTimeout(self._ended.bind(self, sound), 100);
+        return self;
+      }
+
+      // Should this sound loop?
+      var loop = !!(sound._loop || self._sprite[sprite][2]);
+
+      // Fire the ended event.
+      self._emit('end', sound._id);
+
+      // Restart the playback for HTML5 Audio loop.
+      if (!self._webAudio && loop) {
+        self.stop(sound._id, true).play(sound._id);
+      }
+
+      // Restart this timer if on a Web Audio loop.
+      if (self._webAudio && loop) {
+        self._emit('play', sound._id);
+        sound._seek = sound._start || 0;
+        sound._rateSeek = 0;
+        sound._playStart = Howler.ctx.currentTime;
+
+        var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate);
+        self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
+      }
+
+      // Mark the node as paused.
+      if (self._webAudio && !loop) {
+        sound._paused = true;
+        sound._ended = true;
+        sound._seek = sound._start || 0;
+        sound._rateSeek = 0;
+        self._clearTimer(sound._id);
+
+        // Clean up the buffer source.
+        self._cleanBuffer(sound._node);
+
+        // Attempt to auto-suspend AudioContext if no sounds are still playing.
+        Howler._autoSuspend();
+      }
+
+      // When using a sprite, end the track.
+      if (!self._webAudio && !loop) {
+        self.stop(sound._id, true);
+      }
+
+      return self;
+    },
+
+    /**
+     * Clear the end timer for a sound playback.
+     * @param  {Number} id The sound ID.
+     * @return {Howl}
+     */
+    _clearTimer: function(id) {
+      var self = this;
+
+      if (self._endTimers[id]) {
+        // Clear the timeout or remove the ended listener.
+        if (typeof self._endTimers[id] !== 'function') {
+          clearTimeout(self._endTimers[id]);
+        } else {
+          var sound = self._soundById(id);
+          if (sound && sound._node) {
+            sound._node.removeEventListener('ended', self._endTimers[id], false);
+          }
+        }
+
+        delete self._endTimers[id];
+      }
+
+      return self;
+    },
+
+    /**
+     * Return the sound identified by this ID, or return null.
+     * @param  {Number} id Sound ID
+     * @return {Object}    Sound object or null.
+     */
+    _soundById: function(id) {
+      var self = this;
+
+      // Loop through all sounds and find the one with this ID.
+      for (var i=0; i<self._sounds.length; i++) {
+        if (id === self._sounds[i]._id) {
+          return self._sounds[i];
+        }
+      }
+
+      return null;
+    },
+
+    /**
+     * Return an inactive sound from the pool or create a new one.
+     * @return {Sound} Sound playback object.
+     */
+    _inactiveSound: function() {
+      var self = this;
+
+      self._drain();
+
+      // Find the first inactive node to recycle.
+      for (var i=0; i<self._sounds.length; i++) {
+        if (self._sounds[i]._ended) {
+          return self._sounds[i].reset();
+        }
+      }
+
+      // If no inactive node was found, create a new one.
+      return new Sound(self);
+    },
+
+    /**
+     * Drain excess inactive sounds from the pool.
+     */
+    _drain: function() {
+      var self = this;
+      var limit = self._pool;
+      var cnt = 0;
+      var i = 0;
+
+      // If there are less sounds than the max pool size, we are done.
+      if (self._sounds.length < limit) {
+        return;
+      }
+
+      // Count the number of inactive sounds.
+      for (i=0; i<self._sounds.length; i++) {
+        if (self._sounds[i]._ended) {
+          cnt++;
+        }
+      }
+
+      // Remove excess inactive sounds, going in reverse order.
+      for (i=self._sounds.length - 1; i>=0; i--) {
+        if (cnt <= limit) {
+          return;
+        }
+
+        if (self._sounds[i]._ended) {
+          // Disconnect the audio source when using Web Audio.
+          if (self._webAudio && self._sounds[i]._node) {
+            self._sounds[i]._node.disconnect(0);
+          }
+
+          // Remove sounds until we have the pool size.
+          self._sounds.splice(i, 1);
+          cnt--;
+        }
+      }
+    },
+
+    /**
+     * Get all ID's from the sounds pool.
+     * @param  {Number} id Only return one ID if one is passed.
+     * @return {Array}    Array of IDs.
+     */
+    _getSoundIds: function(id) {
+      var self = this;
+
+      if (typeof id === 'undefined') {
+        var ids = [];
+        for (var i=0; i<self._sounds.length; i++) {
+          ids.push(self._sounds[i]._id);
+        }
+
+        return ids;
+      } else {
+        return [id];
+      }
+    },
+
+    /**
+     * Load the sound back into the buffer source.
+     * @param  {Sound} sound The sound object to work with.
+     * @return {Howl}
+     */
+    _refreshBuffer: function(sound) {
+      var self = this;
+
+      // Setup the buffer source for playback.
+      sound._node.bufferSource = Howler.ctx.createBufferSource();
+      sound._node.bufferSource.buffer = cache[self._src];
+
+      // Connect to the correct node.
+      if (sound._panner) {
+        sound._node.bufferSource.connect(sound._panner);
+      } else {
+        sound._node.bufferSource.connect(sound._node);
+      }
+
+      // Setup looping and playback rate.
+      sound._node.bufferSource.loop = sound._loop;
+      if (sound._loop) {
+        sound._node.bufferSource.loopStart = sound._start || 0;
+        sound._node.bufferSource.loopEnd = sound._stop || 0;
+      }
+      sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime);
+
+      return self;
+    },
+
+    /**
+     * Prevent memory leaks by cleaning up the buffer source after playback.
+     * @param  {Object} node Sound's audio node containing the buffer source.
+     * @return {Howl}
+     */
+    _cleanBuffer: function(node) {
+      var self = this;
+      var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0;
+
+      if (Howler._scratchBuffer && node.bufferSource) {
+        node.bufferSource.onended = null;
+        node.bufferSource.disconnect(0);
+        if (isIOS) {
+          try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {}
+        }
+      }
+      node.bufferSource = null;
+
+      return self;
+    },
+
+    /**
+     * Set the source to a 0-second silence to stop any downloading (except in IE).
+     * @param  {Object} node Audio node to clear.
+     */
+    _clearSound: function(node) {
+      var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
+      if (!checkIE) {
+        node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
+      }
+    }
+  };
+
+  /** Single Sound Methods **/
+  /***************************************************************************/
+
+  /**
+   * Setup the sound object, which each node attached to a Howl group is contained in.
+   * @param {Object} howl The Howl parent group.
+   */
+  var Sound = function(howl) {
+    this._parent = howl;
+    this.init();
+  };
+  Sound.prototype = {
+    /**
+     * Initialize a new Sound object.
+     * @return {Sound}
+     */
+    init: function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Setup the default parameters.
+      self._muted = parent._muted;
+      self._loop = parent._loop;
+      self._volume = parent._volume;
+      self._rate = parent._rate;
+      self._seek = 0;
+      self._paused = true;
+      self._ended = true;
+      self._sprite = '__default';
+
+      // Generate a unique ID for this sound.
+      self._id = ++Howler._counter;
+
+      // Add itself to the parent's pool.
+      parent._sounds.push(self);
+
+      // Create the new node.
+      self.create();
+
+      return self;
+    },
+
+    /**
+     * Create and setup a new sound object, whether HTML5 Audio or Web Audio.
+     * @return {Sound}
+     */
+    create: function() {
+      var self = this;
+      var parent = self._parent;
+      var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume;
+
+      if (parent._webAudio) {
+        // Create the gain node for controlling volume (the source will connect to this).
+        self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
+        self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime);
+        self._node.paused = true;
+        self._node.connect(Howler.masterGain);
+      } else if (!Howler.noAudio) {
+        // Get an unlocked Audio object from the pool.
+        self._node = Howler._obtainHtml5Audio();
+
+        // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).
+        self._errorFn = self._errorListener.bind(self);
+        self._node.addEventListener('error', self._errorFn, false);
+
+        // Listen for 'canplaythrough' event to let us know the sound is ready.
+        self._loadFn = self._loadListener.bind(self);
+        self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false);
+
+        // Setup the new audio node.
+        self._node.src = parent._src;
+        self._node.preload = parent._preload === true ? 'auto' : parent._preload;
+        self._node.volume = volume * Howler.volume();
+
+        // Begin loading the source.
+        self._node.load();
+      }
+
+      return self;
+    },
+
+    /**
+     * Reset the parameters of this sound to the original state (for recycle).
+     * @return {Sound}
+     */
+    reset: function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Reset all of the parameters of this sound.
+      self._muted = parent._muted;
+      self._loop = parent._loop;
+      self._volume = parent._volume;
+      self._rate = parent._rate;
+      self._seek = 0;
+      self._rateSeek = 0;
+      self._paused = true;
+      self._ended = true;
+      self._sprite = '__default';
+
+      // Generate a new ID so that it isn't confused with the previous sound.
+      self._id = ++Howler._counter;
+
+      return self;
+    },
+
+    /**
+     * HTML5 Audio error listener callback.
+     */
+    _errorListener: function() {
+      var self = this;
+
+      // Fire an error event and pass back the code.
+      self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0);
+
+      // Clear the event listener.
+      self._node.removeEventListener('error', self._errorFn, false);
+    },
+
+    /**
+     * HTML5 Audio canplaythrough listener callback.
+     */
+    _loadListener: function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Round up the duration to account for the lower precision in HTML5 Audio.
+      parent._duration = Math.ceil(self._node.duration * 10) / 10;
+
+      // Setup a sprite if none is defined.
+      if (Object.keys(parent._sprite).length === 0) {
+        parent._sprite = {__default: [0, parent._duration * 1000]};
+      }
+
+      if (parent._state !== 'loaded') {
+        parent._state = 'loaded';
+        parent._emit('load');
+        parent._loadQueue();
+      }
+
+      // Clear the event listener.
+      self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
+    }
+  };
+
+  /** Helper Methods **/
+  /***************************************************************************/
+
+  var cache = {};
+
+  /**
+   * Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
+   * @param  {Howl} self
+   */
+  var loadBuffer = function(self) {
+    var url = self._src;
+
+    // Check if the buffer has already been cached and use it instead.
+    if (cache[url]) {
+      // Set the duration from the cache.
+      self._duration = cache[url].duration;
+
+      // Load the sound into this Howl.
+      loadSound(self);
+
+      return;
+    }
+
+    if (/^data:[^;]+;base64,/.test(url)) {
+      // Decode the base64 data URI without XHR, since some browsers don't support it.
+      var data = atob(url.split(',')[1]);
+      var dataView = new Uint8Array(data.length);
+      for (var i=0; i<data.length; ++i) {
+        dataView[i] = data.charCodeAt(i);
+      }
+
+      decodeAudioData(dataView.buffer, self);
+    } else {
+      // Load the buffer from the URL.
+      var xhr = new XMLHttpRequest();
+      xhr.open(self._xhr.method, url, true);
+      xhr.withCredentials = self._xhr.withCredentials;
+      xhr.responseType = 'arraybuffer';
+
+      // Apply any custom headers to the request.
+      if (self._xhr.headers) {
+        Object.keys(self._xhr.headers).forEach(function(key) {
+          xhr.setRequestHeader(key, self._xhr.headers[key]);
+        });
+      }
+
+      xhr.onload = function() {
+        // Make sure we get a successful response back.
+        var code = (xhr.status + '')[0];
+        if (code !== '0' && code !== '2' && code !== '3') {
+          self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
+          return;
+        }
+
+        decodeAudioData(xhr.response, self);
+      };
+      xhr.onerror = function() {
+        // If there is an error, switch to HTML5 Audio.
+        if (self._webAudio) {
+          self._html5 = true;
+          self._webAudio = false;
+          self._sounds = [];
+          delete cache[url];
+          self.load();
+        }
+      };
+      safeXhrSend(xhr);
+    }
+  };
+
+  /**
+   * Send the XHR request wrapped in a try/catch.
+   * @param  {Object} xhr XHR to send.
+   */
+  var safeXhrSend = function(xhr) {
+    try {
+      xhr.send();
+    } catch (e) {
+      xhr.onerror();
+    }
+  };
+
+  /**
+   * Decode audio data from an array buffer.
+   * @param  {ArrayBuffer} arraybuffer The audio data.
+   * @param  {Howl}        self
+   */
+  var decodeAudioData = function(arraybuffer, self) {
+    // Fire a load error if something broke.
+    var error = function() {
+      self._emit('loaderror', null, 'Decoding audio data failed.');
+    };
+
+    // Load the sound on success.
+    var success = function(buffer) {
+      if (buffer && self._sounds.length > 0) {
+        cache[self._src] = buffer;
+        loadSound(self, buffer);
+      } else {
+        error();
+      }
+    };
+
+    // Decode the buffer into an audio source.
+    if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
+      Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
+    } else {
+      Howler.ctx.decodeAudioData(arraybuffer, success, error);
+    }
+  }
+
+  /**
+   * Sound is now loaded, so finish setting everything up and fire the loaded event.
+   * @param  {Howl} self
+   * @param  {Object} buffer The decoded buffer sound source.
+   */
+  var loadSound = function(self, buffer) {
+    // Set the duration.
+    if (buffer && !self._duration) {
+      self._duration = buffer.duration;
+    }
+
+    // Setup a sprite if none is defined.
+    if (Object.keys(self._sprite).length === 0) {
+      self._sprite = {__default: [0, self._duration * 1000]};
+    }
+
+    // Fire the loaded event.
+    if (self._state !== 'loaded') {
+      self._state = 'loaded';
+      self._emit('load');
+      self._loadQueue();
+    }
+  };
+
+  /**
+   * Setup the audio context when available, or switch to HTML5 Audio mode.
+   */
+  var setupAudioContext = function() {
+    // If we have already detected that Web Audio isn't supported, don't run this step again.
+    if (!Howler.usingWebAudio) {
+      return;
+    }
+
+    // Check if we are using Web Audio and setup the AudioContext if we are.
+    try {
+      if (typeof AudioContext !== 'undefined') {
+        Howler.ctx = new AudioContext();
+      } else if (typeof webkitAudioContext !== 'undefined') {
+        Howler.ctx = new webkitAudioContext();
+      } else {
+        Howler.usingWebAudio = false;
+      }
+    } catch(e) {
+      Howler.usingWebAudio = false;
+    }
+
+    // If the audio context creation still failed, set using web audio to false.
+    if (!Howler.ctx) {
+      Howler.usingWebAudio = false;
+    }
+
+    // Check if a webview is being used on iOS8 or earlier (rather than the browser).
+    // If it is, disable Web Audio as it causes crashing.
+    var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
+    var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
+    var version = appVersion ? parseInt(appVersion[1], 10) : null;
+    if (iOS && version && version < 9) {
+      var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
+      if (Howler._navigator && !safari) {
+        Howler.usingWebAudio = false;
+      }
+    }
+
+    // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
+    if (Howler.usingWebAudio) {
+      Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
+      Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
+      Howler.masterGain.connect(Howler.ctx.destination);
+    }
+
+    // Re-run the setup on Howler.
+    Howler._setup();
+  };
+
+  // Add support for AMD (Asynchronous Module Definition) libraries such as require.js.
+  if (typeof define === 'function' && define.amd) {
+    define([], function() {
+      return {
+        Howler: Howler,
+        Howl: Howl
+      };
+    });
+  }
+
+  // Add support for CommonJS libraries such as browserify.
+  if (typeof exports !== 'undefined') {
+    exports.Howler = Howler;
+    exports.Howl = Howl;
+  }
+
+  // Add to global in Node.js (for testing, etc).
+  if (typeof global !== 'undefined') {
+    global.HowlerGlobal = HowlerGlobal;
+    global.Howler = Howler;
+    global.Howl = Howl;
+    global.Sound = Sound;
+  } else if (typeof window !== 'undefined') {  // Define globally in case AMD is not available or unused.
+    window.HowlerGlobal = HowlerGlobal;
+    window.Howler = Howler;
+    window.Howl = Howl;
+    window.Sound = Sound;
+  }
+})();
+
+
+/*!
+ *  Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported.
+ *  
+ *  howler.js v2.2.0
+ *  howlerjs.com
+ *
+ *  (c) 2013-2020, James Simpson of GoldFire Studios
+ *  goldfirestudios.com
+ *
+ *  MIT License
+ */
+
+(function() {
+
+  'use strict';
+
+  // Setup default properties.
+  HowlerGlobal.prototype._pos = [0, 0, 0];
+  HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0];
+
+  /** Global Methods **/
+  /***************************************************************************/
+
+  /**
+   * Helper method to update the stereo panning position of all current Howls.
+   * Future Howls will not use this value unless explicitly set.
+   * @param  {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
+   * @return {Howler/Number}     Self or current stereo panning value.
+   */
+  HowlerGlobal.prototype.stereo = function(pan) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self.ctx || !self.ctx.listener) {
+      return self;
+    }
+
+    // Loop through all Howls and update their stereo panning.
+    for (var i=self._howls.length-1; i>=0; i--) {
+      self._howls[i].stereo(pan);
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the position of the listener in 3D cartesian space. Sounds using
+   * 3D position will be relative to the listener's position.
+   * @param  {Number} x The x-position of the listener.
+   * @param  {Number} y The y-position of the listener.
+   * @param  {Number} z The z-position of the listener.
+   * @return {Howler/Array}   Self or current listener position.
+   */
+  HowlerGlobal.prototype.pos = function(x, y, z) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self.ctx || !self.ctx.listener) {
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    y = (typeof y !== 'number') ? self._pos[1] : y;
+    z = (typeof z !== 'number') ? self._pos[2] : z;
+
+    if (typeof x === 'number') {
+      self._pos = [x, y, z];
+
+      if (typeof self.ctx.listener.positionX !== 'undefined') {
+        self.ctx.listener.positionX.setTargetAtTime(self._pos[0], Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.positionY.setTargetAtTime(self._pos[1], Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.positionZ.setTargetAtTime(self._pos[2], Howler.ctx.currentTime, 0.1);
+      } else {
+        self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]);
+      }
+    } else {
+      return self._pos;
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the direction the listener is pointing in the 3D cartesian space.
+   * A front and up vector must be provided. The front is the direction the
+   * face of the listener is pointing, and up is the direction the top of the
+   * listener is pointing. Thus, these values are expected to be at right angles
+   * from each other.
+   * @param  {Number} x   The x-orientation of the listener.
+   * @param  {Number} y   The y-orientation of the listener.
+   * @param  {Number} z   The z-orientation of the listener.
+   * @param  {Number} xUp The x-orientation of the top of the listener.
+   * @param  {Number} yUp The y-orientation of the top of the listener.
+   * @param  {Number} zUp The z-orientation of the top of the listener.
+   * @return {Howler/Array}     Returns self or the current orientation vectors.
+   */
+  HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self.ctx || !self.ctx.listener) {
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    var or = self._orientation;
+    y = (typeof y !== 'number') ? or[1] : y;
+    z = (typeof z !== 'number') ? or[2] : z;
+    xUp = (typeof xUp !== 'number') ? or[3] : xUp;
+    yUp = (typeof yUp !== 'number') ? or[4] : yUp;
+    zUp = (typeof zUp !== 'number') ? or[5] : zUp;
+
+    if (typeof x === 'number') {
+      self._orientation = [x, y, z, xUp, yUp, zUp];
+
+      if (typeof self.ctx.listener.forwardX !== 'undefined') {
+        self.ctx.listener.forwardX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.forwardY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.forwardZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.upX.setTargetAtTime(xUp, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.upY.setTargetAtTime(yUp, Howler.ctx.currentTime, 0.1);
+        self.ctx.listener.upZ.setTargetAtTime(zUp, Howler.ctx.currentTime, 0.1);
+      } else {
+        self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp);
+      }
+    } else {
+      return or;
+    }
+
+    return self;
+  };
+
+  /** Group Methods **/
+  /***************************************************************************/
+
+  /**
+   * Add new properties to the core init.
+   * @param  {Function} _super Core init method.
+   * @return {Howl}
+   */
+  Howl.prototype.init = (function(_super) {
+    return function(o) {
+      var self = this;
+
+      // Setup user-defined default properties.
+      self._orientation = o.orientation || [1, 0, 0];
+      self._stereo = o.stereo || null;
+      self._pos = o.pos || null;
+      self._pannerAttr = {
+        coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360,
+        coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360,
+        coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0,
+        distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse',
+        maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000,
+        panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF',
+        refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1,
+        rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1
+      };
+
+      // Setup event listeners.
+      self._onstereo = o.onstereo ? [{fn: o.onstereo}] : [];
+      self._onpos = o.onpos ? [{fn: o.onpos}] : [];
+      self._onorientation = o.onorientation ? [{fn: o.onorientation}] : [];
+
+      // Complete initilization with howler.js core's init function.
+      return _super.call(this, o);
+    };
+  })(Howl.prototype.init);
+
+  /**
+   * Get/set the stereo panning of the audio source for this sound or all in the group.
+   * @param  {Number} pan  A value of -1.0 is all the way left and 1.0 is all the way right.
+   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
+   * @return {Howl/Number}    Returns self or the current stereo panning value.
+   */
+  Howl.prototype.stereo = function(pan, id) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable.
+    if (self._state !== 'loaded') {
+      self._queue.push({
+        event: 'stereo',
+        action: function() {
+          self.stereo(pan, id);
+        }
+      });
+
+      return self;
+    }
+
+    // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist.
+    var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo';
+
+    // Setup the group's stereo panning if no ID is passed.
+    if (typeof id === 'undefined') {
+      // Return the group's stereo panning if no parameters are passed.
+      if (typeof pan === 'number') {
+        self._stereo = pan;
+        self._pos = [pan, 0, 0];
+      } else {
+        return self._stereo;
+      }
+    }
+
+    // Change the streo panning of one or all sounds in group.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      // Get the sound.
+      var sound = self._soundById(ids[i]);
+
+      if (sound) {
+        if (typeof pan === 'number') {
+          sound._stereo = pan;
+          sound._pos = [pan, 0, 0];
+
+          if (sound._node) {
+            // If we are falling back, make sure the panningModel is equalpower.
+            sound._pannerAttr.panningModel = 'equalpower';
+
+            // Check if there is a panner setup and create a new one if not.
+            if (!sound._panner || !sound._panner.pan) {
+              setupPanner(sound, pannerType);
+            }
+
+            if (pannerType === 'spatial') {
+              if (typeof sound._panner.positionX !== 'undefined') {
+                sound._panner.positionX.setValueAtTime(pan, Howler.ctx.currentTime);
+                sound._panner.positionY.setValueAtTime(0, Howler.ctx.currentTime);
+                sound._panner.positionZ.setValueAtTime(0, Howler.ctx.currentTime);
+              } else {
+                sound._panner.setPosition(pan, 0, 0);
+              }
+            } else {
+              sound._panner.pan.setValueAtTime(pan, Howler.ctx.currentTime);
+            }
+          }
+
+          self._emit('stereo', sound._id);
+        } else {
+          return sound._stereo;
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the 3D spatial position of the audio source for this sound or group relative to the global listener.
+   * @param  {Number} x  The x-position of the audio source.
+   * @param  {Number} y  The y-position of the audio source.
+   * @param  {Number} z  The z-position of the audio source.
+   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
+   * @return {Howl/Array}    Returns self or the current 3D spatial position: [x, y, z].
+   */
+  Howl.prototype.pos = function(x, y, z, id) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // If the sound hasn't loaded, add it to the load queue to change position when capable.
+    if (self._state !== 'loaded') {
+      self._queue.push({
+        event: 'pos',
+        action: function() {
+          self.pos(x, y, z, id);
+        }
+      });
+
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    y = (typeof y !== 'number') ? 0 : y;
+    z = (typeof z !== 'number') ? -0.5 : z;
+
+    // Setup the group's spatial position if no ID is passed.
+    if (typeof id === 'undefined') {
+      // Return the group's spatial position if no parameters are passed.
+      if (typeof x === 'number') {
+        self._pos = [x, y, z];
+      } else {
+        return self._pos;
+      }
+    }
+
+    // Change the spatial position of one or all sounds in group.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      // Get the sound.
+      var sound = self._soundById(ids[i]);
+
+      if (sound) {
+        if (typeof x === 'number') {
+          sound._pos = [x, y, z];
+
+          if (sound._node) {
+            // Check if there is a panner setup and create a new one if not.
+            if (!sound._panner || sound._panner.pan) {
+              setupPanner(sound, 'spatial');
+            }
+
+            if (typeof sound._panner.positionX !== 'undefined') {
+              sound._panner.positionX.setValueAtTime(x, Howler.ctx.currentTime);
+              sound._panner.positionY.setValueAtTime(y, Howler.ctx.currentTime);
+              sound._panner.positionZ.setValueAtTime(z, Howler.ctx.currentTime);
+            } else {
+              sound._panner.setPosition(x, y, z);
+            }
+          }
+
+          self._emit('pos', sound._id);
+        } else {
+          return sound._pos;
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the direction the audio source is pointing in the 3D cartesian coordinate
+   * space. Depending on how direction the sound is, based on the `cone` attributes,
+   * a sound pointing away from the listener can be quiet or silent.
+   * @param  {Number} x  The x-orientation of the source.
+   * @param  {Number} y  The y-orientation of the source.
+   * @param  {Number} z  The z-orientation of the source.
+   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
+   * @return {Howl/Array}    Returns self or the current 3D spatial orientation: [x, y, z].
+   */
+  Howl.prototype.orientation = function(x, y, z, id) {
+    var self = this;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // If the sound hasn't loaded, add it to the load queue to change orientation when capable.
+    if (self._state !== 'loaded') {
+      self._queue.push({
+        event: 'orientation',
+        action: function() {
+          self.orientation(x, y, z, id);
+        }
+      });
+
+      return self;
+    }
+
+    // Set the defaults for optional 'y' & 'z'.
+    y = (typeof y !== 'number') ? self._orientation[1] : y;
+    z = (typeof z !== 'number') ? self._orientation[2] : z;
+
+    // Setup the group's spatial orientation if no ID is passed.
+    if (typeof id === 'undefined') {
+      // Return the group's spatial orientation if no parameters are passed.
+      if (typeof x === 'number') {
+        self._orientation = [x, y, z];
+      } else {
+        return self._orientation;
+      }
+    }
+
+    // Change the spatial orientation of one or all sounds in group.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      // Get the sound.
+      var sound = self._soundById(ids[i]);
+
+      if (sound) {
+        if (typeof x === 'number') {
+          sound._orientation = [x, y, z];
+
+          if (sound._node) {
+            // Check if there is a panner setup and create a new one if not.
+            if (!sound._panner) {
+              // Make sure we have a position to setup the node with.
+              if (!sound._pos) {
+                sound._pos = self._pos || [0, 0, -0.5];
+              }
+
+              setupPanner(sound, 'spatial');
+            }
+
+            if (typeof sound._panner.orientationX !== 'undefined') {
+              sound._panner.orientationX.setValueAtTime(x, Howler.ctx.currentTime);
+              sound._panner.orientationY.setValueAtTime(y, Howler.ctx.currentTime);
+              sound._panner.orientationZ.setValueAtTime(z, Howler.ctx.currentTime);
+            } else {
+              sound._panner.setOrientation(x, y, z);
+            }
+          }
+
+          self._emit('orientation', sound._id);
+        } else {
+          return sound._orientation;
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /**
+   * Get/set the panner node's attributes for a sound or group of sounds.
+   * This method can optionall take 0, 1 or 2 arguments.
+   *   pannerAttr() -> Returns the group's values.
+   *   pannerAttr(id) -> Returns the sound id's values.
+   *   pannerAttr(o) -> Set's the values of all sounds in this Howl group.
+   *   pannerAttr(o, id) -> Set's the values of passed sound id.
+   *
+   *   Attributes:
+   *     coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
+   *                      inside of which there will be no volume reduction.
+   *     coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
+   *                      outside of which the volume will be reduced to a constant value of `coneOuterGain`.
+   *     coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the
+   *                     `coneOuterAngle`. It is a linear value in the range `[0, 1]`.
+   *     distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from
+   *                     listener. Can be `linear`, `inverse` or `exponential.
+   *     maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume
+   *                   will not be reduced any further.
+   *     refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener.
+   *                   This is simply a variable of the distance model and has a different effect depending on which model
+   *                   is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance.
+   *     rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a
+   *                     variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]`
+   *                     with `inverse` and `exponential`.
+   *     panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio.
+   *                     Can be `HRTF` or `equalpower`.
+   *
+   * @return {Howl/Object} Returns self or current panner attributes.
+   */
+  Howl.prototype.pannerAttr = function() {
+    var self = this;
+    var args = arguments;
+    var o, id, sound;
+
+    // Stop right here if not using Web Audio.
+    if (!self._webAudio) {
+      return self;
+    }
+
+    // Determine the values based on arguments.
+    if (args.length === 0) {
+      // Return the group's panner attribute values.
+      return self._pannerAttr;
+    } else if (args.length === 1) {
+      if (typeof args[0] === 'object') {
+        o = args[0];
+
+        // Set the grou's panner attribute values.
+        if (typeof id === 'undefined') {
+          if (!o.pannerAttr) {
+            o.pannerAttr = {
+              coneInnerAngle: o.coneInnerAngle,
+              coneOuterAngle: o.coneOuterAngle,
+              coneOuterGain: o.coneOuterGain,
+              distanceModel: o.distanceModel,
+              maxDistance: o.maxDistance,
+              refDistance: o.refDistance,
+              rolloffFactor: o.rolloffFactor,
+              panningModel: o.panningModel
+            };
+          }
+
+          self._pannerAttr = {
+            coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle,
+            coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle,
+            coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain,
+            distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel,
+            maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance,
+            refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance,
+            rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor,
+            panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel
+          };
+        }
+      } else {
+        // Return this sound's panner attribute values.
+        sound = self._soundById(parseInt(args[0], 10));
+        return sound ? sound._pannerAttr : self._pannerAttr;
+      }
+    } else if (args.length === 2) {
+      o = args[0];
+      id = parseInt(args[1], 10);
+    }
+
+    // Update the values of the specified sounds.
+    var ids = self._getSoundIds(id);
+    for (var i=0; i<ids.length; i++) {
+      sound = self._soundById(ids[i]);
+
+      if (sound) {
+        // Merge the new values into the sound.
+        var pa = sound._pannerAttr;
+        pa = {
+          coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : pa.coneInnerAngle,
+          coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : pa.coneOuterAngle,
+          coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : pa.coneOuterGain,
+          distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : pa.distanceModel,
+          maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : pa.maxDistance,
+          refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : pa.refDistance,
+          rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : pa.rolloffFactor,
+          panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : pa.panningModel
+        };
+
+        // Update the panner values or create a new panner if none exists.
+        var panner = sound._panner;
+        if (panner) {
+          panner.coneInnerAngle = pa.coneInnerAngle;
+          panner.coneOuterAngle = pa.coneOuterAngle;
+          panner.coneOuterGain = pa.coneOuterGain;
+          panner.distanceModel = pa.distanceModel;
+          panner.maxDistance = pa.maxDistance;
+          panner.refDistance = pa.refDistance;
+          panner.rolloffFactor = pa.rolloffFactor;
+          panner.panningModel = pa.panningModel;
+        } else {
+          // Make sure we have a position to setup the node with.
+          if (!sound._pos) {
+            sound._pos = self._pos || [0, 0, -0.5];
+          }
+
+          // Create a new panner node.
+          setupPanner(sound, 'spatial');
+        }
+      }
+    }
+
+    return self;
+  };
+
+  /** Single Sound Methods **/
+  /***************************************************************************/
+
+  /**
+   * Add new properties to the core Sound init.
+   * @param  {Function} _super Core Sound init method.
+   * @return {Sound}
+   */
+  Sound.prototype.init = (function(_super) {
+    return function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Setup user-defined default properties.
+      self._orientation = parent._orientation;
+      self._stereo = parent._stereo;
+      self._pos = parent._pos;
+      self._pannerAttr = parent._pannerAttr;
+
+      // Complete initilization with howler.js core Sound's init function.
+      _super.call(this);
+
+      // If a stereo or position was specified, set it up.
+      if (self._stereo) {
+        parent.stereo(self._stereo);
+      } else if (self._pos) {
+        parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
+      }
+    };
+  })(Sound.prototype.init);
+
+  /**
+   * Override the Sound.reset method to clean up properties from the spatial plugin.
+   * @param  {Function} _super Sound reset method.
+   * @return {Sound}
+   */
+  Sound.prototype.reset = (function(_super) {
+    return function() {
+      var self = this;
+      var parent = self._parent;
+
+      // Reset all spatial plugin properties on this sound.
+      self._orientation = parent._orientation;
+      self._stereo = parent._stereo;
+      self._pos = parent._pos;
+      self._pannerAttr = parent._pannerAttr;
+
+      // If a stereo or position was specified, set it up.
+      if (self._stereo) {
+        parent.stereo(self._stereo);
+      } else if (self._pos) {
+        parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
+      } else if (self._panner) {
+        // Disconnect the panner.
+        self._panner.disconnect(0);
+        self._panner = undefined;
+        parent._refreshBuffer(self);
+      }
+
+      // Complete resetting of the sound.
+      return _super.call(this);
+    };
+  })(Sound.prototype.reset);
+
+  /** Helper Methods **/
+  /***************************************************************************/
+
+  /**
+   * Create a new panner node and save it on the sound.
+   * @param  {Sound} sound Specific sound to setup panning on.
+   * @param {String} type Type of panner to create: 'stereo' or 'spatial'.
+   */
+  var setupPanner = function(sound, type) {
+    type = type || 'spatial';
+
+    // Create the new panner node.
+    if (type === 'spatial') {
+      sound._panner = Howler.ctx.createPanner();
+      sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
+      sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
+      sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
+      sound._panner.distanceModel = sound._pannerAttr.distanceModel;
+      sound._panner.maxDistance = sound._pannerAttr.maxDistance;
+      sound._panner.refDistance = sound._pannerAttr.refDistance;
+      sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
+      sound._panner.panningModel = sound._pannerAttr.panningModel;
+
+      if (typeof sound._panner.positionX !== 'undefined') {
+        sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
+        sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
+        sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
+      } else {
+        sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
+      }
+
+      if (typeof sound._panner.orientationX !== 'undefined') {
+        sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
+        sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
+        sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
+      } else {
+        sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
+      }
+    } else {
+      sound._panner = Howler.ctx.createStereoPanner();
+      sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
+    }
+
+    sound._panner.connect(sound._node);
+
+    // Update the connections.
+    if (!sound._paused) {
+      sound._parent.pause(sound._id, true).play(sound._id, true);
+    }
+  };
+})();

Diff do ficheiro suprimidas por serem muito extensas
+ 1 - 0
js/howler/howler.min.js


Diff do ficheiro suprimidas por serem muito extensas
+ 1 - 0
js/howler/howler.spatial.min.js


+ 390 - 0
lib/flutter_sound_player_web.dart

@@ -0,0 +1,390 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+@JS()
+library flutter_sound;
+
+import 'dart:async';
+import 'dart:html' as html;
+import 'dart:typed_data' show Uint8List;
+
+import 'package:meta/meta.dart';
+import 'package:flutter_sound_platform_interface/flutter_sound_platform_interface.dart';
+import 'package:flutter_sound_platform_interface/flutter_sound_player_platform_interface.dart';
+import 'package:flutter_web_plugins/flutter_web_plugins.dart';
+import 'dart:io';
+import 'package:js/js.dart';
+import 'package:logger/logger.dart' show Level, Logger;
+
+// ====================================  JS  =======================================================
+
+@JS('newPlayerInstance')
+external FlutterSoundPlayer newPlayerInstance(
+    FlutterSoundPlayerCallback theCallBack, List<Function> callbackTable);
+
+@JS('FlutterSoundPlayer')
+class FlutterSoundPlayer {
+  @JS('releaseMediaPlayer')
+  external int releaseMediaPlayer();
+
+  @JS('initializeMediaPlayer')
+  external int initializeMediaPlayer();
+
+  @JS('setAudioFocus')
+  external int setAudioFocus(
+    int focus,
+    int category,
+    int mode,
+    int? audioFlags,
+    int device,
+  );
+
+  @JS('getPlayerState')
+  external int getPlayerState();
+
+  @JS('isDecoderSupported')
+  external bool isDecoderSupported(
+    int codec,
+  );
+
+  @JS('setSubscriptionDuration')
+  external int setSubscriptionDuration(int duration);
+
+  @JS('startPlayer')
+  external int startPlayer(int? codec, Uint8List? fromDataBuffer,
+      String? fromURI, int? numChannels, int? sampleRate);
+
+  @JS('feed')
+  external int feed(
+    Uint8List? data,
+  );
+
+  @JS('startPlayerFromTrack')
+  external int startPlayerFromTrack(
+    int progress,
+    int duration,
+    Map<String, dynamic> track,
+    bool canPause,
+    bool canSkipForward,
+    bool canSkipBackward,
+    bool defaultPauseResume,
+    bool removeUIWhenStopped,
+  );
+
+  @JS('nowPlaying')
+  external int nowPlaying(
+    int progress,
+    int duration,
+    Map<String, dynamic>? track,
+    bool? canPause,
+    bool? canSkipForward,
+    bool? canSkipBackward,
+    bool? defaultPauseResume,
+  );
+
+  @JS('stopPlayer')
+  external int stopPlayer();
+
+  @JS('resumePlayer')
+  external int pausePlayer();
+
+  @JS('')
+  external int resumePlayer();
+
+  @JS('seekToPlayer')
+  external int seekToPlayer(int duration);
+
+  @JS('setVolume')
+  external int setVolume(double? volume);
+
+  @JS('setSpeed')
+  external int setSpeed(double speed);
+
+  @JS('setUIProgressBar')
+  external int setUIProgressBar(int duration, int progress);
+}
+
+List<Function> callbackTable = [
+  allowInterop((FlutterSoundPlayerCallback cb, int position, int duration) {
+    cb.updateProgress(
+      duration: duration,
+      position: position,
+    );
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state) {
+    cb.updatePlaybackState(
+      state,
+    );
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int ln) {
+    cb.needSomeFood(
+      ln,
+    );
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state) {
+    cb.audioPlayerFinished(
+      state,
+    );
+  }),
+  allowInterop(
+      (FlutterSoundPlayerCallback cb, int state, bool success, int duration) {
+    cb.startPlayerCompleted(
+      state,
+      success,
+      duration,
+    );
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state, bool success) {
+    cb.pausePlayerCompleted(state, success);
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state, bool success) {
+    cb.resumePlayerCompleted(state, success);
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state, bool success) {
+    cb.stopPlayerCompleted(state, success);
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state, bool success) {
+    cb.openPlayerCompleted(state, success);
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int state, bool success) {
+    cb.closePlayerCompleted(state, success);
+  }),
+  allowInterop((FlutterSoundPlayerCallback cb, int level, String msg) {
+    cb.log(Level.values[level], msg);
+  }),
+];
+
+//=========================================================================================================
+
+/// The web implementation of [FlutterSoundPlatform].
+///
+/// This class implements the `package:flutter_sound_player` functionality for the web.
+///
+
+class FlutterSoundPlayerWeb
+    extends FlutterSoundPlayerPlatform //implements FlutterSoundPlayerCallback
+{
+  static List<String> defaultExtensions = [
+    "flutter_sound.aac", // defaultCodec
+    "flutter_sound.aac", // aacADTS
+    "flutter_sound.opus", // opusOGG
+    "flutter_sound_opus.caf", // opusCAF
+    "flutter_sound.mp3", // mp3
+    "flutter_sound.ogg", // vorbisOGG
+    "flutter_sound.pcm", // pcm16
+    "flutter_sound.wav", // pcm16WAV
+    "flutter_sound.aiff", // pcm16AIFF
+    "flutter_sound_pcm.caf", // pcm16CAF
+    "flutter_sound.flac", // flac
+    "flutter_sound.mp4", // aacMP4
+    "flutter_sound.amr", // amrNB
+    "flutter_sound.amr", // amrWB
+    "flutter_sound.pcm", // pcm8
+    "flutter_sound.pcm", // pcmFloat32
+  ];
+
+  /// Registers this class as the default instance of [FlutterSoundPlatform].
+  static void registerWith(Registrar registrar) {
+    FlutterSoundPlayerPlatform.instance = FlutterSoundPlayerWeb();
+  }
+
+  /* ctor */ MethodChannelFlutterSoundPlayer() {}
+
+//============================================ Session manager ===================================================================
+
+  List<FlutterSoundPlayer?> _slots = [];
+  FlutterSoundPlayer? getWebSession(FlutterSoundPlayerCallback callback) {
+    return _slots[findSession(callback)];
+  }
+
+//==============================================================================================================================
+
+  @override
+  Future<void>? resetPlugin(
+    FlutterSoundPlayerCallback callback,
+  ) {
+    callback.log(Level.debug, '---> resetPlugin');
+    for (int i = 0; i < _slots.length; ++i) {
+      callback.log(Level.debug, "Releasing slot #$i");
+      _slots[i]!.releaseMediaPlayer();
+    }
+    _slots = [];
+    callback.log(Level.debug, '<--- resetPlugin');
+    return null;
+  }
+
+  @override
+  Future<int> openPlayer(FlutterSoundPlayerCallback callback,
+      {required Level logLevel, bool voiceProcessing = false}) async {
+    // openAudioSessionCompleter = new Completer<bool>();
+    // await invokeMethod( callback, 'initializeMediaPlayer', {'focus': focus.index, 'category': category.index, 'mode': mode.index, 'audioFlags': audioFlags, 'device': device.index, 'withUI': withUI ? 1 : 0 ,},) ;
+    // return  openAudioSessionCompleter.future ;
+    int slotno = findSession(callback);
+    if (slotno < _slots.length) {
+      assert(_slots[slotno] == null);
+      _slots[slotno] = newPlayerInstance(callback, callbackTable);
+    } else {
+      assert(slotno == _slots.length);
+      _slots.add(newPlayerInstance(callback, callbackTable));
+    }
+    return _slots[slotno]!.initializeMediaPlayer();
+  }
+
+  @override
+  Future<int> closePlayer(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    int slotno = findSession(callback);
+    int r = _slots[slotno]!.releaseMediaPlayer();
+    _slots[slotno] = null;
+    return r;
+  }
+
+  @override
+  Future<int> getPlayerState(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    return getWebSession(callback)!.getPlayerState();
+  }
+
+  @override
+  Future<Map<String, Duration>> getProgress(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    // Map<String, int> m = await invokeMethod( callback, 'getPlayerState', null,) as Map;
+    Map<String, Duration> r = {
+      'duration': Duration.zero,
+      'progress': Duration.zero,
+    };
+    return r;
+  }
+
+  @override
+  Future<bool> isDecoderSupported(
+    FlutterSoundPlayerCallback callback, {
+    required Codec codec,
+  }) async {
+    return getWebSession(callback)!.isDecoderSupported(codec.index);
+  }
+
+  @override
+  Future<int> setSubscriptionDuration(
+    FlutterSoundPlayerCallback callback, {
+    Duration? duration,
+  }) async {
+    return getWebSession(callback)!
+        .setSubscriptionDuration(duration!.inMilliseconds);
+  }
+
+  @override
+  Future<int> startPlayer(FlutterSoundPlayerCallback callback,
+      {Codec? codec,
+      Uint8List? fromDataBuffer,
+      String? fromURI,
+      int? numChannels,
+      int? sampleRate}) async {
+    // startPlayerCompleter = new Completer<Map>();
+    // await invokeMethod( callback, 'startPlayer', {'codec': codec.index, 'fromDataBuffer': fromDataBuffer, 'fromURI': fromURI, 'numChannels': numChannels, 'sampleRate': sampleRate},) ;
+    // return  startPlayerCompleter.future ;
+    // String s = "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3";
+    if (codec == null) codec = Codec.defaultCodec;
+    if (fromDataBuffer != null) {
+      if (fromURI != null) {
+        throw Exception(
+            "You may not specify both 'fromURI' and 'fromDataBuffer' parameters");
+      }
+      //js.context.callMethod('playAudioFromBuffer', [fromDataBuffer]);
+      //playAudioFromBuffer(fromDataBuffer);
+      // .......................return getWebSession(callback).playAudioFromBuffer(fromDataBuffer);
+      //playAudioFromBuffer3(fromDataBuffer);
+      //Directory tempDir = await getTemporaryDirectory();
+      /*
+                        String path = defaultExtensions[codec.index];
+                        File filOut = File(path);
+                        IOSink sink = filOut.openWrite();
+                        sink.add(fromDataBuffer.toList());
+                        fromURI = path;
+                         */
+    }
+    //js.context.callMethod('playAudioFromURL', [fromURI]);
+    callback.log(Level.debug, 'startPlayer FromURI : $fromURI');
+    return getWebSession(callback)!.startPlayer(
+        codec.index, fromDataBuffer, fromURI, numChannels, sampleRate);
+  }
+
+  @override
+  Future<int> startPlayerFromMic(FlutterSoundPlayerCallback callback,
+      {int? numChannels, int? sampleRate}) {
+    throw Exception('StartPlayerFromMic() is not implemented on Flutter Web');
+  }
+
+  @override
+  Future<int> feed(
+    FlutterSoundPlayerCallback callback, {
+    Uint8List? data,
+  }) async {
+    return getWebSession(callback)!.feed(data);
+  }
+
+  @override
+  Future<int> stopPlayer(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    return getWebSession(callback)!.stopPlayer();
+  }
+
+  @override
+  Future<int> pausePlayer(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    return getWebSession(callback)!.pausePlayer();
+  }
+
+  @override
+  Future<int> resumePlayer(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    return getWebSession(callback)!.resumePlayer();
+  }
+
+  @override
+  Future<int> seekToPlayer(FlutterSoundPlayerCallback callback,
+      {Duration? duration}) async {
+    return getWebSession(callback)!.seekToPlayer(duration!.inMilliseconds);
+  }
+
+  Future<int> setVolume(FlutterSoundPlayerCallback callback,
+      {double? volume}) async {
+    return getWebSession(callback)!.setVolume(volume);
+  }
+
+  Future<int> setSpeed(FlutterSoundPlayerCallback callback,
+      {required double speed}) async {
+    return getWebSession(callback)!.setSpeed(speed);
+  }
+
+  Future<String> getResourcePath(
+    FlutterSoundPlayerCallback callback,
+  ) async {
+    return '';
+  }
+
+  @override
+  Future<void>? setLogLeve(
+      FlutterSoundPlayerCallback callback, Level loglevel) {}
+}

+ 221 - 0
lib/flutter_sound_recorder_web.dart

@@ -0,0 +1,221 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+@JS()
+library flutter_sound;
+
+import 'dart:async';
+import 'dart:html' as html;
+
+import 'package:meta/meta.dart';
+import 'package:flutter_sound_platform_interface/flutter_sound_platform_interface.dart';
+import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
+import 'package:flutter_web_plugins/flutter_web_plugins.dart';
+import 'dart:typed_data';
+import 'package:logger/logger.dart' show Level , Logger;
+
+import 'package:js/js.dart';
+
+//========================================  JS  ===============================================================
+
+@JS('newRecorderInstance')
+external FlutterSoundRecorder newRecorderInstance(FlutterSoundRecorderCallback callBack, List<Function> callbackTable);
+
+@JS('FlutterSoundRecorder')
+class FlutterSoundRecorder
+{
+        @JS('newInstance')
+        external static FlutterSoundRecorder newInstance(FlutterSoundRecorderCallback callBack, List<Function> callbackTable);
+
+        @JS('initializeFlautoRecorder')
+        external void initializeFlautoRecorder();
+
+        @JS('releaseFlautoRecorder')
+        external void releaseFlautoRecorder();
+
+        @JS('setAudioFocus')
+        external void setAudioFocus(int focus, int category, int mode, int? audioFlags, int device);
+
+        @JS('isEncoderSupported')
+        external bool isEncoderSupported(int codec);
+
+        @JS('setSubscriptionDuration')
+        external void setSubscriptionDuration(int duration);
+
+        @JS('startRecorder')
+        external void startRecorder(String? path, int? sampleRate, int? numChannels, int? bitRate, int codec, bool? toStream, int audioSource);
+
+        @JS('stopRecorder')
+        external void stopRecorder();
+
+        @JS('pauseRecorder')
+        external void pauseRecorder();
+
+        @JS('resumeRecorder')
+        external void resumeRecorder();
+
+        @JS('getRecordURL')
+        external String getRecordURL(String path,);
+
+        @JS('deleteRecord')
+        external bool deleteRecord(String path,);
+
+}
+
+
+List<Function> callbackTable =
+[
+        allowInterop( (FlutterSoundRecorderCallback cb,  int duration, double dbPeakLevel)               { cb.updateRecorderProgress(duration: duration, dbPeakLevel: dbPeakLevel);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb, {Uint8List? data})                               { cb.recordingData(data: data);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int state, bool success)                        { cb.startRecorderCompleted(state, success);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int state, bool success)                        { cb.pauseRecorderCompleted(state, success);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int state, bool success)                        { cb.resumeRecorderCompleted(state, success);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int state, bool success, String url)            { cb.stopRecorderCompleted(state, success, url);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int state, bool success)                        { cb.openRecorderCompleted(state, success);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int state, bool success)                        { cb.closeRecorderCompleted(state, success);} ),
+        allowInterop( (FlutterSoundRecorderCallback cb,  int level, String msg)                          { cb.log(Level.values[level], msg);} ),
+];
+
+
+//============================================================================================================================
+
+/// The web implementation of [FlutterSoundRecorderPlatform].
+///
+/// This class implements the `package:FlutterSoundPlayerPlatform` functionality for the web.
+class FlutterSoundRecorderWeb extends FlutterSoundRecorderPlatform //implements FlutterSoundRecorderCallback
+{
+
+        /// Registers this class as the default instance of [FlutterSoundRecorderPlatform].
+        static void registerWith(Registrar registrar)
+        {
+                FlutterSoundRecorderPlatform.instance = FlutterSoundRecorderWeb();
+        }
+
+
+
+
+        List<FlutterSoundRecorder?> _slots = [];
+        FlutterSoundRecorder? getWebSession(FlutterSoundRecorderCallback callback)
+        {
+                return _slots[findSession(callback)];
+        }
+
+
+//================================================================================================================
+
+        @override
+        Future<void>?   resetPlugin(FlutterSoundRecorderCallback callback,) async
+        {
+                callback.log(Level.debug, '---> resetPlugin');
+                for (int i = 0; i < _slots.length; ++i)
+                {
+                        callback.log(Level.debug, "Releasing slot #$i");
+                        _slots[i]!.releaseFlautoRecorder();
+                }
+                _slots = [];
+                callback.log(Level.debug, '<--- resetPlugin');
+                return null;
+        }
+
+        @override
+        Future<void> openRecorder(FlutterSoundRecorderCallback callback, {required Level logLevel,}) async
+        {
+                int slotno = findSession(callback);
+                if (slotno < _slots.length)
+                {
+                        assert (_slots[slotno] == null);
+                        _slots[slotno] = newRecorderInstance(callback, callbackTable);
+                } else
+                {
+                        assert(slotno == _slots.length);
+                        _slots.add( newRecorderInstance(callback, callbackTable));
+                }
+                getWebSession(callback)!.initializeFlautoRecorder();
+        }
+
+
+        @override
+        Future<void> closeRecorder(FlutterSoundRecorderCallback callback, ) async
+        {
+                int slotno = findSession(callback);
+                _slots[slotno]!.releaseFlautoRecorder();
+                _slots[slotno] = null;
+        }
+
+        @override
+        Future<bool> isEncoderSupported(FlutterSoundRecorderCallback callback, {required Codec codec,}) async
+        {
+                return getWebSession(callback)!.isEncoderSupported(codec.index);
+        }
+
+        @override
+        Future<void> setSubscriptionDuration(FlutterSoundRecorderCallback callback, {Duration? duration,}) async
+        {
+                getWebSession(callback)!.setSubscriptionDuration(duration!.inMilliseconds);
+        }
+
+        @override
+        Future<void> startRecorder(FlutterSoundRecorderCallback callback,
+            {
+                    String? path,
+                    int? sampleRate,
+                    int? numChannels,
+                    int? bitRate,
+                    Codec? codec,
+                    bool? toStream,
+                    AudioSource? audioSource,
+            }) async
+        {
+                getWebSession(callback)!.startRecorder(path, sampleRate, numChannels, bitRate, codec!.index, toStream, audioSource!.index,);
+        }
+
+        @override
+        Future<void> stopRecorder(FlutterSoundRecorderCallback callback,  ) async
+        {
+                FlutterSoundRecorder? session = getWebSession(callback);
+                if (session != null)
+                        session.stopRecorder();
+                else
+                        callback.log(Level.debug, 'Recorder already stopped');
+        }
+
+        @override
+        Future<void> pauseRecorder(FlutterSoundRecorderCallback callback,  ) async
+        {
+                getWebSession(callback)!.pauseRecorder();
+        }
+
+        @override
+        Future<void> resumeRecorder(FlutterSoundRecorderCallback callback, ) async
+        {
+                getWebSession(callback)!.resumeRecorder();
+        }
+
+        @override
+        Future<String> getRecordURL (FlutterSoundRecorderCallback callback, String path ) async
+        {
+                return  getWebSession(callback)!.getRecordURL(path);
+        }
+
+        @override
+        Future<bool> deleteRecord (FlutterSoundRecorderCallback callback, String path ) async
+        {
+                return getWebSession(callback)!.deleteRecord(path);
+        }
+
+}

+ 149 - 0
lib/flutter_sound_web.dart

@@ -0,0 +1,149 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+import 'dart:async';
+import 'dart:html' as html;
+
+import 'package:meta/meta.dart';
+import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
+import 'package:flutter_web_plugins/flutter_web_plugins.dart';
+import 'package:flutter_sound_web/flutter_sound_player_web.dart';
+import 'package:flutter_sound_web/flutter_sound_recorder_web.dart';
+import 'package:flutter/foundation.dart';
+
+class ImportJsLibraryWeb {
+        /// Injects the library by its [url]
+        static Future<void> import(String url) {
+                return _importJSLibraries([url]);
+        }
+
+        static html.ScriptElement _createScriptTag(String library) {
+                final html.ScriptElement script = html.ScriptElement()
+                        ..type = "text/javascript"
+                        ..charset = "utf-8"
+                        ..async = true
+                //..defer = true
+                        ..src = library;
+                return script;
+        }
+
+        /// Injects a bunch of libraries in the <head> and returns a
+        /// Future that resolves when all load.
+        static Future<void> _importJSLibraries(List<String> libraries) {
+                final List<Future<void>> loading = <Future<void>>[];
+                final head = html.querySelector('head')!;
+
+                libraries.forEach((String library) {
+                        if (!isImported(library)) {
+                                final scriptTag = _createScriptTag(library);
+                                head.children.add(scriptTag);
+                                loading.add(scriptTag.onLoad.first);
+                        }
+                });
+
+                return Future.wait(loading);
+        }
+
+        static bool _isLoaded(html.Element head, String url) {
+                if (url.startsWith("./")) {
+                        url = url.replaceFirst("./", "");
+                }
+                for (var element in head.children) {
+                        if (element is html.ScriptElement) {
+                                if (element.src.endsWith(url)) {
+                                        return true;
+                                }
+                        }
+                }
+                return false;
+        }
+
+        static bool isImported(String url) {
+                final html.Element  head = html.querySelector('head')!;
+                return _isLoaded(head, url);
+        }
+}
+
+
+class ImportJsLibrary {
+        static Future<void> import(String url) {
+                if (kIsWeb)
+                        return ImportJsLibraryWeb.import(url);
+                else
+                        return Future.value(null);
+        }
+
+        static bool isImported(String url) {
+                if (kIsWeb) {
+                        return ImportJsLibraryWeb.isImported(url);
+                } else {
+                        return false;
+                }
+        }
+
+        static registerWith(dynamic _) {
+                // useful for flutter registrar
+        }
+}
+
+String _libraryUrl(String url, String pluginName) {
+        if (url.startsWith("./")) {
+                url = url.replaceFirst("./", "");
+                return "./assets/packages/$pluginName/$url";
+        }
+        if (url.startsWith("assets/")) {
+                return "./assets/packages/$pluginName/$url";
+        } else {
+                return url;
+        }
+}
+
+void importJsLibrary({required String url, required String flutterPluginName}) {
+        if (flutterPluginName == null) {
+                ImportJsLibrary.import(url);
+        } else {
+                ImportJsLibrary.import(_libraryUrl(url, flutterPluginName));
+        }
+}
+
+bool isJsLibraryImported(String url, {required String flutterPluginName}) {
+        if (flutterPluginName == null) {
+                return ImportJsLibrary.isImported(url);
+        } else {
+                return ImportJsLibrary.isImported(_libraryUrl(url, flutterPluginName));
+        }
+}
+
+
+
+/// The web implementation of [FlutterSoundRecorderPlatform].
+///
+/// This class implements the `package:FlutterSoundPlayerPlatform` functionality for the web.
+class FlutterSoundPlugin //extends FlutterSoundPlatform
+{
+        /// Registers this class as the default instance of [FlutterSoundPlatform].
+        static void registerWith(Registrar registrar)
+        {
+                FlutterSoundPlayerWeb.registerWith(registrar);
+                FlutterSoundRecorderWeb.registerWith(registrar);
+                importJsLibrary(url: "./howler/howler.js", flutterPluginName: "flutter_sound_web");
+                importJsLibrary(url: "./src/flutter_sound.js", flutterPluginName: "flutter_sound_web");
+                importJsLibrary(url: "./src/flutter_sound_player.js", flutterPluginName: "flutter_sound_web");
+                importJsLibrary(url: "./src/flutter_sound_recorder.js", flutterPluginName: "flutter_sound_web");
+        }
+}

+ 52 - 0
pubspec.yaml

@@ -0,0 +1,52 @@
+name: flutter_sound_web
+version: 9.2.13
+description: Flutter plugin that relates to sound like audio and recorder.
+#author: dooboolab<dooboolab@gmail.com>
+homepage: https://github.com/dooboolab/flutter_sound
+environment:
+    sdk: '>=2.12.0 <3.0.0'
+    flutter: ">=1.12.0"
+
+# 0.1.y+z is compatible with 1.0.0, if you land a breaking change bump
+# the version to 2.0.0.
+# See more details: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0
+
+flutter:
+  plugin:
+    platforms:
+      web:
+        pluginClass: FlutterSoundPlugin
+        fileName: flutter_sound_web.dart
+        
+  assets:
+  - howler/howler.js
+  - src/flutter_sound.js
+  - src/flutter_sound_player.js
+  - src/flutter_sound_recorder.js
+  - src/Mp3LameEncoder.min.js
+  - src/OggVorbisEncoder.min.js
+  - src/WavAudioEncoder.min.js
+  - howler/howler.js
+  - src/WebAudioRecorder.js
+  - src/WebAudioRecorderMp3.js
+  - src/WebAudioRecorderOgg.js
+  - src/WebAudioRecorderWav.js
+
+
+
+dependencies:
+  flutter_sound_platform_interface: 9.2.13
+#    path: ../flutter_sound_platform_interface # Flutter Sound Dir
+  flutter:
+    sdk: flutter
+  logger: ^1.0.0
+  flutter_web_plugins:
+    sdk: flutter
+  meta: ^1.3.0
+  js: ^0.6.3
+
+dev_dependencies:
+  flutter_test:
+    sdk: flutter
+  pedantic: ^1.11.0
+

Diff do ficheiro suprimidas por serem muito extensas
+ 0 - 0
src/Mp3LameEncoder.min.js


BIN
src/Mp3LameEncoder.min.js.mem


Diff do ficheiro suprimidas por serem muito extensas
+ 0 - 0
src/OggVorbisEncoder.min.js


BIN
src/OggVorbisEncoder.min.js.mem


+ 1 - 0
src/WavAudioEncoder.min.js

@@ -0,0 +1 @@
+(function(n){var a=Math.min,s=Math.max;var e=function(n,a,e){var s=e.length;for(var t=0;t<s;++t)n.setUint8(a+t,e.charCodeAt(t))};var t=function(t,e){this.sampleRate=t;this.numChannels=e;this.numSamples=0;this.dataViews=[]};t.prototype.encode=function(r){var t=r[0].length,u=this.numChannels,h=new DataView(new ArrayBuffer(t*u*2)),o=0;for(var e=0;e<t;++e)for(var n=0;n<u;++n){var i=r[n][e]*32767;h.setInt16(o,i<0?s(i,-32768):a(i,32767),true);o+=2}this.dataViews.push(h);this.numSamples+=t};t.prototype.finish=function(s){var n=this.numChannels*this.numSamples*2,t=new DataView(new ArrayBuffer(44));e(t,0,"RIFF");t.setUint32(4,36+n,true);e(t,8,"WAVE");e(t,12,"fmt ");t.setUint32(16,16,true);t.setUint16(20,1,true);t.setUint16(22,this.numChannels,true);t.setUint32(24,this.sampleRate,true);t.setUint32(28,this.sampleRate*4,true);t.setUint16(32,this.numChannels*2,true);t.setUint16(34,16,true);e(t,36,"data");t.setUint32(40,n,true);this.dataViews.unshift(t);var a=new Blob(this.dataViews,{type:"audio/wav"});this.cleanup();return a};t.prototype.cancel=t.prototype.cleanup=function(){delete this.dataViews};n.WavAudioEncoder=t})(self);

+ 199 - 0
src/WebAudioRecorder.js

@@ -0,0 +1,199 @@
+(function(window) {
+  // internal: same as jQuery.extend(true, args...)
+  var extend = function() {
+    var target = arguments[0],
+        sources = [].slice.call(arguments, 1);
+    for (var i = 0; i < sources.length; ++i) {
+      var src = sources[i];
+      for (key in src) {
+        var val = src[key];
+        target[key] = typeof val === "object"
+          ? extend(typeof target[key] === "object" ? target[key] : {}, val)
+          : val;
+      }
+    }
+    return target;
+  };
+
+  var WORKER_FILE = {
+    wav: "WebAudioRecorderWav.js",
+    ogg: "WebAudioRecorderOgg.js",
+    mp3: "WebAudioRecorderMp3.js"
+  };
+
+  // default configs
+  var CONFIGS = {
+    workerDir: "/",     // worker scripts dir (end with /)
+    numChannels: 2,     // number of channels
+    encoding: "wav",    // encoding (can be changed at runtime)
+
+    // runtime options
+    options: {
+      timeLimit: 300,           // recording time limit (sec)
+      encodeAfterRecord: false, // process encoding after recording
+      progressInterval: 1000,   // encoding progress report interval (millisec)
+      bufferSize: undefined,    // buffer size (use browser default)
+
+      // encoding-specific options
+      wav: {
+        mimeType: "audio/wav"
+      },
+      ogg: {
+        mimeType: "audio/ogg",
+        quality: 0.5            // (VBR only): quality = [-0.1 .. 1]
+      },
+      mp3: {
+        mimeType: "audio/mpeg",
+        bitRate: 160            // (CBR only): bit rate = [64 .. 320]
+      }
+    }
+  };
+
+  // constructor
+  var WebAudioRecorder = function(sourceNode, configs) {
+    extend(this, CONFIGS, configs || {});
+    this.context = sourceNode.context;
+    if (this.context.createScriptProcessor == null)
+      this.context.createScriptProcessor = this.context.createJavaScriptNode;
+    this.input = this.context.createGain();
+    sourceNode.connect(this.input);
+    this.buffer = [];
+    this.initWorker();
+  };
+
+  // instance methods
+  extend(WebAudioRecorder.prototype, {
+    isRecording: function() { return this.processor != null; },
+
+    setEncoding: function(encoding) {
+      if (this.isRecording())
+        this.error("setEncoding: cannot set encoding during recording");
+      else if (this.encoding !== encoding) {
+        this.encoding = encoding;
+        this.initWorker();
+      }
+    },
+
+    setOptions: function(options) {
+      if (this.isRecording())
+        this.error("setOptions: cannot set options during recording");
+      else {
+        extend(this.options, options);
+        this.worker.postMessage({ command: "options", options: this.options });
+      }
+    },
+
+    startRecording: function() {
+      if (this.isRecording())
+        this.error("startRecording: previous recording is running");
+      else {
+        var numChannels = this.numChannels,
+            buffer = this.buffer,
+            worker = this.worker;
+        this.processor = this.context.createScriptProcessor(
+                                this.options.bufferSize,
+                                this.numChannels, this.numChannels);
+        this.input.connect(this.processor);
+        this.processor.connect(this.context.destination);
+        this.processor.onaudioprocess = function(event) {
+          for (var ch = 0; ch < numChannels; ++ch)
+            buffer[ch] = event.inputBuffer.getChannelData(ch);
+          worker.postMessage({ command: "record", buffer: buffer });
+        };
+        this.worker.postMessage({
+          command: "start",
+          bufferSize: this.processor.bufferSize
+        });
+        this.startTime = Date.now();
+      }
+    },
+
+    recordingTime: function() {
+      return this.isRecording() ? (Date.now() - this.startTime) * 0.001 : null;
+    },
+
+    cancelRecording: function() {
+      if (this.isRecording()) {
+        this.input.disconnect();
+        this.processor.disconnect();
+        delete this.processor;
+        this.worker.postMessage({ command: "cancel" });
+      } else
+        this.error("cancelRecording: no recording is running");
+    },
+
+    finishRecording: function() {
+      if (this.isRecording()) {
+        this.input.disconnect();
+        this.processor.disconnect();
+        delete this.processor;
+        this.worker.postMessage({ command: "finish" });
+      } else
+        this.error("finishRecording: no recording is running");
+    },
+
+    cancelEncoding: function() {
+      if (this.options.encodeAfterRecord)
+        if (this.isRecording())
+          this.error("cancelEncoding: recording is not finished");
+        else {
+          this.onEncodingCanceled(this);
+          this.initWorker();
+        }
+      else
+        this.error("cancelEncoding: invalid method call");
+    },
+
+    initWorker: function() {
+      if (this.worker != null)
+        this.worker.terminate();
+      this.onEncoderLoading(this, this.encoding);
+      this.worker = new Worker(this.workerDir + WORKER_FILE[this.encoding]);
+      var _this = this;
+      this.worker.onmessage = function(event) {
+        var data = event.data;
+        switch (data.command) {
+          case "loaded":
+            _this.onEncoderLoaded(_this, _this.encoding);
+            break;
+          case "timeout":
+            _this.onTimeout(_this);
+            break;
+          case "progress":
+            _this.onEncodingProgress(_this, data.progress);
+            break;
+          case "complete":
+            _this.onComplete(_this, data.blob);
+            break;
+          case "error":
+            _this.error(data.message);
+        }
+      };
+      this.worker.postMessage({
+        command: "init",
+        config: {
+          sampleRate: this.context.sampleRate,
+          numChannels: this.numChannels
+        },
+        options: this.options
+      });
+    },
+
+    error: function(message) {
+      this.onError(this, "WebAudioRecorder.js:" + message);
+    },
+
+    // event handlers
+    onEncoderLoading: function(recorder, encoding) {},
+    onEncoderLoaded: function(recorder, encoding) {},
+    onTimeout: function(recorder) { recorder.finishRecording(); },
+    onEncodingProgress: function (recorder, progress) {},
+    onEncodingCanceled: function(recorder) {},
+    onComplete: function(recorder, blob) {
+      recorder.onError(recorder, "WebAudioRecorder.js: You must override .onComplete event");
+    },
+    onError: function(recorder, message) { console.log(message); }
+  });
+
+  window.WebAudioRecorder = WebAudioRecorder;
+})(window);

+ 91 - 0
src/WebAudioRecorderMp3.js

@@ -0,0 +1,91 @@
+importScripts("Mp3LameEncoder.min.js");
+
+var NUM_CH = 2, // constant
+    sampleRate = 44100,
+    options = undefined,
+    maxBuffers = undefined,
+    encoder = undefined,
+    recBuffers = undefined,
+    bufferCount = 0;
+
+function error(message) {
+  self.postMessage({ command: "error", message: "mp3: " + message });
+}
+
+function init(data) {
+  if (data.config.numChannels === NUM_CH) {
+    sampleRate = data.config.sampleRate;
+    options = data.options;
+  } else
+    error("numChannels must be " + NUM_CH);
+};
+
+function setOptions(opt) {
+  if (encoder || recBuffers)
+    error("cannot set options during recording");
+  else
+    options = opt;
+}
+
+function start(bufferSize) {
+  maxBuffers = Math.ceil(options.timeLimit * sampleRate / bufferSize);
+  if (options.encodeAfterRecord)
+    recBuffers = [];
+  else
+    encoder = new Mp3LameEncoder(sampleRate, options.mp3.bitRate);
+}
+
+function record(buffer) {
+  if (bufferCount++ < maxBuffers)
+    if (encoder)
+      encoder.encode(buffer);
+    else
+      recBuffers.push(buffer);
+  else
+    self.postMessage({ command: "timeout" });
+};
+
+function postProgress(progress) {
+  self.postMessage({ command: "progress", progress: progress });
+};
+
+function finish() {
+  if (recBuffers) {
+    postProgress(0);
+    encoder = new Mp3LameEncoder(sampleRate, options.mp3.bitRate);
+    var timeout = Date.now() + options.progressInterval;
+    while (recBuffers.length > 0) {
+      encoder.encode(recBuffers.shift());
+      var now = Date.now();
+      if (now > timeout) {
+        postProgress((bufferCount - recBuffers.length) / bufferCount);
+        timeout = now + options.progressInterval;
+      }
+    }
+    postProgress(1);
+  }
+  self.postMessage({
+    command: "complete",
+    blob: encoder.finish(options.mp3.mimeType)
+  });
+  cleanup();
+};
+
+function cleanup() {
+  encoder = recBuffers = undefined;
+  bufferCount = 0;
+}
+
+self.onmessage = function(event) {
+  var data = event.data;
+  switch (data.command) {
+    case "init":    init(data);                 break;
+    case "options": setOptions(data.options);   break;
+    case "start":   start(data.bufferSize);     break;
+    case "record":  record(data.buffer);        break;
+    case "finish":  finish();                   break;
+    case "cancel":  cleanup();
+  }
+};
+
+self.postMessage({ command: "loaded" });

+ 89 - 0
src/WebAudioRecorderOgg.js

@@ -0,0 +1,89 @@
+importScripts("OggVorbisEncoder.min.js");
+
+var sampleRate = 44100,
+    numChannels = 2,
+    options = undefined,
+    maxBuffers = undefined,
+    encoder = undefined,
+    recBuffers = undefined,
+    bufferCount = 0;
+
+function error(message) {
+  self.postMessage({ command: "error", message: "ogg: " + message });
+}
+
+function init(data) {
+  sampleRate = data.config.sampleRate;
+  numChannels = data.config.numChannels;
+  options = data.options;
+};
+
+function setOptions(opt) {
+  if (encoder || recBuffers)
+    error("cannot set options during recording");
+  else
+    options = opt;
+}
+
+function start(bufferSize) {
+  maxBuffers = Math.ceil(options.timeLimit * sampleRate / bufferSize);
+  if (options.encodeAfterRecord)
+    recBuffers = [];
+  else
+    encoder = new OggVorbisEncoder(sampleRate, numChannels, options.ogg.quality);
+}
+
+function record(buffer) {
+  if (bufferCount++ < maxBuffers)
+    if (encoder)
+      encoder.encode(buffer);
+    else
+      recBuffers.push(buffer);
+  else
+    self.postMessage({ command: "timeout" });
+};
+
+function postProgress(progress) {
+  self.postMessage({ command: "progress", progress: progress });
+};
+
+function finish() {
+  if (recBuffers) {
+    postProgress(0);
+    encoder = new OggVorbisEncoder(sampleRate, numChannels, options.ogg.quality);
+    var timeout = Date.now() + options.progressInterval;
+    while (recBuffers.length > 0) {
+      encoder.encode(recBuffers.shift());
+      var now = Date.now();
+      if (now > timeout) {
+        postProgress((bufferCount - recBuffers.length) / bufferCount);
+        timeout = now + options.progressInterval;
+      }
+    }
+    postProgress(1);
+  }
+  self.postMessage({
+    command: "complete",
+    blob: encoder.finish(options.ogg.mimeType)
+  });
+  cleanup();
+};
+
+function cleanup() {
+  encoder = recBuffers = undefined;
+  bufferCount = 0;
+}
+
+self.onmessage = function(event) {
+  var data = event.data;
+  switch (data.command) {
+    case "init":    init(data);                 break;
+    case "options": setOptions(data.options);   break;
+    case "start":   start(data.bufferSize);     break;
+    case "record":  record(data.buffer);        break;
+    case "finish":  finish();                   break;
+    case "cancel":  cleanup();
+  }
+};
+
+self.postMessage({ command: "loaded" });

+ 89 - 0
src/WebAudioRecorderWav.js

@@ -0,0 +1,89 @@
+importScripts("WavAudioEncoder.min.js");
+
+var sampleRate = 44100,
+    numChannels = 2,
+    options = undefined,
+    maxBuffers = undefined,
+    encoder = undefined,
+    recBuffers = undefined,
+    bufferCount = 0;
+
+function error(message) {
+  self.postMessage({ command: "error", message: "wav: " + message });
+}
+
+function init(data) {
+  sampleRate = data.config.sampleRate;
+  numChannels = data.config.numChannels;
+  options = data.options;
+};
+
+function setOptions(opt) {
+  if (encoder || recBuffers)
+    error("cannot set options during recording");
+  else
+    options = opt;
+}
+
+function start(bufferSize) {
+  maxBuffers = Math.ceil(options.timeLimit * sampleRate / bufferSize);
+  if (options.encodeAfterRecord)
+    recBuffers = [];
+  else
+    encoder = new WavAudioEncoder(sampleRate, numChannels);
+}
+
+function record(buffer) {
+  if (bufferCount++ < maxBuffers)
+    if (encoder)
+      encoder.encode(buffer);
+    else
+      recBuffers.push(buffer);
+  else
+    self.postMessage({ command: "timeout" });
+};
+
+function postProgress(progress) {
+  self.postMessage({ command: "progress", progress: progress });
+};
+
+function finish() {
+  if (recBuffers) {
+    postProgress(0);
+    encoder = new WavAudioEncoder(sampleRate, numChannels);
+    var timeout = Date.now() + options.progressInterval;
+    while (recBuffers.length > 0) {
+      encoder.encode(recBuffers.shift());
+      var now = Date.now();
+      if (now > timeout) {
+        postProgress((bufferCount - recBuffers.length) / bufferCount);
+        timeout = now + options.progressInterval;
+      }
+    }
+    postProgress(1);
+  }
+  self.postMessage({
+    command: "complete",
+    blob: encoder.finish(options.wav.mimeType)
+  });
+  cleanup();
+};
+
+function cleanup() {
+  encoder = recBuffers = undefined;
+  bufferCount = 0;
+}
+
+self.onmessage = function(event) {
+  var data = event.data;
+  switch (data.command) {
+    case "init":    init(data);                 break;
+    case "options": setOptions(data.options);   break;
+    case "start":   start(data.bufferSize);     break;
+    case "record":  record(data.buffer);        break;
+    case "finish":  finish();                   break;
+    case "cancel":  cleanup();
+  }
+};
+
+self.postMessage({ command: "loaded" });

+ 159 - 0
src/flutter_sound.js

@@ -0,0 +1,159 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+const VERSION = '8.2.0'
+
+
+const VERBOSE = 0;
+const DBG = 1;
+const INFO = 2;
+const WARNING = 3;
+const ERROR = 4;
+const WTF = 5;
+const NOTHING = 6;
+
+
+
+
+const codec =
+                {
+                        defaultCodec:   'defaultCodec',
+                        aacADTS:        'aacADTS',
+                        opusOGG:        'opusOGG',
+                        opusCAF:        'opusCAF',
+                        mp3:            'mp3',
+                        vorbisOGG:      'vorbisOGG',
+                        pcm16:          'pcm16',
+                        pcm16WAV:       'pcm16WAV',
+                        pcm16AIFF:      'pcm16AIFF',
+                        pcm16CAF:       'pcm16CAF',
+                        flac:           'flac',
+                        aacMP4:         'aacMP4',
+                        amrNB:          'amrNB',
+                        amrWB:          'amrWB',
+                        pcm8:           'pcm8',
+                        pcmFloat32:     'pcmFloat32',
+                        pcmWebM:        'pcmWebM',
+                        opusWebM:       'opusWebM',
+                        vorbisWebM:     'vorbisWebM',
+                };
+
+
+const tabCodec =
+                [
+                        codec.opusWebM, // codec.defaultCodec,
+                        codec.aacADTS,
+                        codec.opusOGG,
+                        codec.opusCAF,
+                        codec.mp3,
+                        codec.vorbisOGG,
+                        codec.pcm16,
+                        codec.pcm16WAV,
+                        codec.pcm16AIFF,
+                        codec.pcm16CAF,
+                        codec.flac,
+                        codec.aacMP4,
+                        codec.amrNB,
+                        codec.amrWB,
+                        codec.pcm8,
+                        codec.pcmFloat32,
+                        codec.pcmWebM,
+                        codec.opusWebM,
+                        codec.vorbisWebM,
+                ];
+
+const mime_types =
+                [
+                        'audio/webm\;codecs=opus', // defaultCodec,
+                        'audio/aac', // aacADTS,
+                        'audio/opus\;codecs=opus', // opusOGG,
+                        'audio/x-caf', // opusCAF,
+                        'audio/mp3', // mp3,
+                        'audio/ogg\;codecs=vorbis', // vorbisOGG,
+                        'audio/pcm', // pcm16,
+                        'audio/wav\;codecs=1', // pcm16WAV,
+                        'audio/aiff', // pcm16AIFF,
+                        'audio/x-caf', // pcm16CAF,
+                        'audio/x-flac', // flac,
+                        'audio/mp4', // aacMP4,
+                        'audio/AMR', // amrNB,
+                        'audio/AMR-WB', // amrWB,
+                        'audio/pcm', // pcm8,
+                        'audio/pcm', // pcmFloat32,
+                        'audio/webm\;codecs=pcm', // pcmWebM,
+                        'audio/webm\;codecs=opus', // opusWebM,
+                        'audio/webm\;codecs=vorbis', // vorbisWebM
+                ];
+
+const tabFormat =
+                [
+                        'opus', // defaultCodec,
+                        'aac', // aacADTS,
+                        'opus', // opusOGG,
+                        'caf', // opusCAF,
+                        'mp3', // mp3,
+                        'vorbis', // vorbisOGG,
+                        '', // pcm16,
+                        'wav', // pcm16WAV,
+                        'aiff', // pcm16AIFF,
+                        'caf', // pcm16CAF,
+                        'flac', // flac,
+                        'mp4', // aacMP4,
+                        'AMR', // amrNB,
+                        'AMR-WB', // amrWB,
+                        '', // pcm8,
+                        '', // pcmFloat32,
+                        'pcm', // pcmWebM,
+                        'opus', // opusWebM,
+                        'webm', // vorbisWebM
+
+                ];
+
+
+
+var instanceNumber = 0;
+var lastUrl = '';
+
+
+
+function getRecordURL( aPath,)
+{
+        var path ;
+        var myStorage;
+        if ((aPath == null) || (aPath == ''))
+        {
+                path = lastUrl;
+        } else
+        {
+                path =  aPath;
+
+        }
+        if (path.substring(0,1) == '/')
+        {
+                myStorage = window.localStorage;
+        } else
+        {
+                myStorage = window.sessionStorage;
+        }
+
+        var url = myStorage.getItem(path);
+        return url;
+}
+
+
+

+ 411 - 0
src/flutter_sound_player.js

@@ -0,0 +1,411 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+
+const PLAYER_VERSION = '8.2.0'
+
+function newPlayerInstance(aCallback, callbackTable) { return new FlutterSoundPlayer(aCallback, callbackTable); }
+
+const IS_PLAYER_STOPPED = 0;
+const IS_PLAYER_PLAYING = 1;
+const IS_PLAYER_PAUSED = 2;
+
+const CB_updateProgress = 0;
+const CB_updatePlaybackState = 1;
+const CB_needSomeFood = 2;
+const CB_audioPlayerFinished = 3;
+const CB_startPlayerCompleted = 4;
+const CB_pausePlayerCompleted = 5;
+const CB_resumePlayerCompleted = 6;
+const CB_stopPlayerCompleted = 7;
+const CB_openPlayerCompleted = 8;
+const CB_closePlayerCompleted = 9;
+const CB_player_log = 10;
+
+var instanceNumber = 1;
+
+class FlutterSoundPlayer {
+
+        static newInstance(aCallback, callbackTable) { return new FlutterSoundPlayer(aCallback, callbackTable); }
+
+        constructor(aCallback, callbackTable) {
+                this.callback = aCallback;
+                this.callbackTable = callbackTable;
+                this.howl = null;
+                this.temporaryBlob = null;
+                this.status = IS_PLAYER_STOPPED;
+                //this.deltaTime = 0;
+                this.subscriptionDuration = 0;
+                this.duration = 0;
+                this.instanceNo = instanceNumber;
+                this.callbackTable[CB_player_log](this.callback, DBG, 'Instance Number : ' + this.instanceNo.toString())
+                ++instanceNumber;
+        }
+
+        initializeMediaPlayer(focus, category, mode, audioFlags, device, withUI) {
+                //this.callback.openAudioSessionCompleted(true);
+                this.status = IS_PLAYER_STOPPED;
+                this.callbackTable[CB_openPlayerCompleted](this.callback, this.getPlayerState(), true);
+                return this.getPlayerState();
+        }
+
+        releaseMediaPlayer() {
+                this.status = IS_PLAYER_STOPPED;
+                this.callbackTable[CB_closePlayerCompleted](this.callback, this.getPlayerState(), true);
+                return this.getPlayerState();
+        }
+
+
+
+        playAudioFromURL(path, codec) {
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> playAudioFromURL : ' + path);
+                var me = this;
+                var howl = new Howl
+                        ({
+                                src: [path],
+                                format: tabFormat[codec],
+
+                                onload: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onload');
+					me.howl.play();
+                                },
+
+                                onplay: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onplay');
+                                        me.duration = Math.ceil(howl.duration() * 1000);
+                                        me.status = IS_PLAYER_PLAYING;
+                                        if (me.pauseResume != IS_PLAYER_PAUSED) {
+                                                me.callbackTable[CB_startPlayerCompleted](me.callback, me.getPlayerState(), true, me.duration); // Duration is unknown
+
+                                        } else {
+                                                me.callbackTable[CB_resumePlayerCompleted](me.callback, me.getPlayerState(), true);
+
+                                        }
+                                        me.startTimer();
+
+                                },
+
+                                onplayerror: function () {
+                                        me.callbackTable[CB_player_log](me.callback, ERROR, 'onplayerror');
+                                        me.stop();
+                                },
+
+                                onend: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onend');
+                                        me.stop();
+                                        me.status = IS_PLAYER_STOPPED;
+                                        me.callbackTable[CB_audioPlayerFinished](me.callback, me.getPlayerState());
+                                },
+
+                                onloaderror: function () {
+                                        me.callbackTable[CB_player_log](me.callback, ERROR, 'onloaderror');
+                                        me.stop()
+                                },
+
+                                onpause: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onpause');
+                                        me.status = IS_PLAYER_PAUSED;
+                                        me.callbackTable[CB_pausePlayerCompleted](me.callback, me.getPlayerState(), true);
+
+                                },
+
+                                onstop: function () {
+                                        me.callbackTable[CB_player_log](me.callback, DBG, 'onstop');
+                                        me.status = IS_PLAYER_STOPPED;
+                                        me.howl = null;
+                                        me.callbackTable[CB_stopPlayerCompleted](me.callback, me.getPlayerState(), true);
+                                },
+
+                                onseek: function () {
+                                        //me.callbackTable[CB_player_log](me.callback, DBG, 'onseek');
+                                },
+                        });
+
+                this.howl = howl;
+                if (this.latentVolume != null && this.latentVolume >= 0)
+                        this.howl.volume(this.latentVolume);
+                if (this.latentSpeed != null && this.latentSpeed >= 0)
+                        this.howl.rate(this.latentSpeed);
+                if (this.latentSeek != null && this.latentSeek >= 0)
+                        this.seekToPlayer(this.latentSeek);
+                this.pauseResume = IS_PLAYER_PLAYING;
+                // howl.play(); // This now done in 'onload'
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- playAudioFromURL');
+                return this.getPlayerState();
+        }
+
+
+        /* ACTUALLY NOT USED
+                playAudioFromBuffer(dataBuffer) // Actually not used
+                {
+        
+                        var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+                        var source = audioCtx.createBufferSource();
+                        me.callbackTable[CB_player_log](me.callback, DBG, dataBuffer.constructor.name)
+                        audioCtx.decodeAudioData
+                        (
+                                dataBuffer, //dataBuffer.buffer,
+                                function(buffer)
+                                {
+                                        source.buffer = buffer;
+        
+                                        source.connect(audioCtx.destination);
+                                        source.loop = false;
+                                           // start the source playing
+                                        source.start();
+                                },
+                                function(e){ me.callbackTable[CB_player_log](me.callback, DBG, "Error with decoding audio data" + e.err); }
+                        );
+                        this.callback.startPlayerCompleted(777);
+                        return 0; // playAudioFromBuffer() does not support sound Duration
+        }
+        */
+
+
+
+
+        setAudioFocus(focus, category, mode, audioFlags, device,) {
+                return this.getPlayerState();
+        }
+
+
+        isDecoderSupported(codec,) {
+                return true; // TODO
+        }
+
+        setSubscriptionDuration(duration) {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'setSubscriptionDuration');
+                this.subscriptionDuration = duration;
+                if (duration > 0 && this.howl != null)
+                        this.startTimer();
+                return this.getPlayerState();
+        }
+
+
+        getRecordURL(path,) {
+                var myStorage;
+                if ((path == null) || (path == '')) {
+                        return null;
+                }
+                if (path.includes("/"))
+                        return path;
+                if (path.substring(0, 1) == '/') {
+                        myStorage = window.localStorage;
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'localStorage');
+                } else {
+                        myStorage = window.sessionStorage;
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'sessionStorage');
+                }
+
+                var url = myStorage.getItem(path);
+                return url
+
+        }
+
+        startPlayer(codec, fromDataBuffer, fromURI, numChannels, sampleRate) {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> startPlayer');
+                this.stop();
+                if (this.temporaryBlob != null) {
+                        URL.revokeObjectURL(this.temporaryBlob);
+                        this.temporaryBlob = null;
+                }
+                if (fromDataBuffer != null) {
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'startPlayer : ' + fromDataBuffer.constructor.name);
+                        var anArray = [fromDataBuffer]; // new Array(fromDataBuffer);
+                        // return this.playAudioFromBuffer(fromDataBuffer.buffer); // playAudioFromBuffer() is ctually not used
+                        var blob = new Blob(anArray, { 'type': mime_types[codec] });
+                        fromURI = URL.createObjectURL(blob);
+                        this.temporaryBlob = fromURI;
+
+                }
+                if (fromURI == null || fromURI == '') {
+                        fromURI = lastUrl;
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'Playing lastUrl : ' + lastUrl);
+                }
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'startPlayer : ' + fromURI);
+                var url = this.getRecordURL(fromURI);
+
+                if (url != null) {
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'startPlayer : ' + url.constructor.name);
+                        fromURI = url;
+                }
+                //this.deltaTime = 0;
+                this.pauseResume = IS_PLAYER_PLAYING; // Maybe too early
+                this.playAudioFromURL(url, codec);
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- startPlayer');
+                return this.getPlayerState();
+        }
+
+        feed(data,) {
+                return this.getPlayerState();
+        }
+
+        startPlayerFromTrack(progress, duration, track, canPause, canSkipForward, canSkipBackward, defaultPauseResume, removeUIWhenStopped,) {
+                return 0; // TODO
+        }
+
+        nowPlaying(progress, duration, track, canPause, canSkipForward, canSkipBackward, defaultPauseResume,) {
+                return this.getPlayerState();
+        }
+
+        stop() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> stop');
+                this.stopTimer();
+
+
+                if (this.temporaryBlob != null)
+                        URL.revokeObjectURL(this.temporaryBlob);
+                this.temporaryBlob = null;
+
+                if (this.howl != null) {
+                        this.howl.stop();
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- stop');
+                        return true;
+                }
+                else {
+                        this.status = IS_PLAYER_STOPPED; // Maybe too early ?
+                        //this.callbackTable[CB_stopPlayerCompleted](this.callback,  IS_PLAYER_STOPPED, true);
+                        this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- stop');
+                        return false;
+                }
+
+        }
+
+        stopPlayer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> stopPlayer');
+                //if (this.howl == null)
+                //this.callbackTable[CB_stopPlayerCompleted](this.callback,  IS_PLAYER_STOPPED, true);
+                if (!this.stop())
+                        this.callbackTable[CB_stopPlayerCompleted](this.callback, this.getPlayerState(), true);
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- stopPlayer');
+                return this.getPlayerState();
+        }
+
+        getPlayerState() {
+                if (this.howl == null) {
+                        this.status = IS_PLAYER_STOPPED;
+                }
+                return this.status;
+        }
+
+        pausePlayer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> pausePlayer');
+                this.stopTimer();
+
+                if (this.getPlayerState() == IS_PLAYER_PLAYING) {
+                        //this.status = IS_PLAYER_PAUSED; // Maybe too early
+                        this.howl.pause();
+                } else {
+                        this.callbackTable[CB_pausePlayerCompleted](this.callback, this.getPlayerState(), false);
+                }
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- pausePlayer');
+                return this.getPlayerState();
+        }
+
+        resumePlayer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: ---> resumePlayer');
+                if (this.getPlayerState() == IS_PLAYER_PAUSED) {
+                        //this.status = IS_PLAYER_PLAYING; // Maybe too early
+                        this.pauseResume = IS_PLAYER_PAUSED;
+                        this.howl.play();
+                } else {
+                        this.callbackTable[CB_resumePlayerCompleted](this.callback, this.getPlayerState(), false);
+                }
+                this.startTimer();
+
+                this.callbackTable[CB_player_log](this.callback, DBG, 'JS: <--- resumePlayer');
+                return this.getPlayerState();
+        }
+
+        seekToPlayer(duration) {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> seekToPlayer()');
+                if (this.howl != null) {
+                        this.latentSeek = 0;
+                        this.countDownDate = new Date().getTime() - duration;
+                        //this.deltaTime = 0;
+                        this.howl.seek(duration / 1000);
+                } else
+                        this.latentSeek = duration;
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- seekToPlayer()');
+                return this.getPlayerState();
+        }
+
+        setVolume(volume) {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> setVolume()');
+                this.latentVolume = volume;
+                if (this.howl != null)
+                        this.howl.volume(volume);
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- setVolume()');
+                return this.getPlayerState();
+        }
+
+
+        setSpeed(speed) {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> setSpeed()');
+                this.latentSpeed = speed;
+                if (this.howl != null)
+                        this.howl.rate(speed);
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- setSpeed()');
+                return this.getPlayerState();
+        }
+
+        setUIProgressBar(duration, progress) {
+                return this.getPlayerState();
+        }
+
+
+        startTimer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, '---> startTimer()');
+                this.stopTimer();
+                var me = this;
+
+                if (this.subscriptionDuration > 0) {
+                        this.countDownDate = new Date().getTime();
+                        this.timerId = setInterval
+                                (
+                                        function () {
+                                                //var now = new Date().getTime();
+                                                //var distance = now - me.countDownDate;
+                                                //distance += me.deltaTime;
+                                                var pos = Math.floor(me.howl.seek() * 1000);
+                                                if (pos > me.duration)
+                                                        pos = me.duration;
+                                                me.callbackTable[CB_updateProgress](me.callback, pos/*me.deltaTime + distance*/, me.duration);
+
+                                        },
+                                        this.subscriptionDuration
+                                );
+                }
+                this.callbackTable[CB_player_log](this.callback, DBG, '<--- startTimer()');
+        }
+
+        stopTimer() {
+                this.callbackTable[CB_player_log](this.callback, DBG, 'stopTimer()');
+                if (this.timerId != null) {
+                        clearInterval(this.timerId);
+                        //var now = new Date().getTime();
+                        //var distance = now - this.countDownDate;
+                        //this.deltaTime += distance;
+                        this.timerId = null;
+                }
+        }
+
+}

+ 429 - 0
src/flutter_sound_recorder.js

@@ -0,0 +1,429 @@
+/*
+ * Copyright 2018, 2019, 2020 Dooboolab.
+ *
+ * This file is part of Flutter-Sound.
+ *
+ * Flutter-Sound is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3 (LGPL-V3), as published by
+ * the Free Software Foundation.
+ *
+ * Flutter-Sound is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with Flutter-Sound.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+const RECORDER_VERSION = '8.2.0'
+
+const IS_RECORDER_PAUSED = 1;
+const IS_RECORDER_RECORDING = 2;
+const IS_RECORDER_STOPPED = 0;
+
+function newRecorderInstance(aCallback, callbackTable) { return new FlutterSoundRecorder(aCallback, callbackTable); }
+
+
+const CB_updateRecorderProgress = 0;
+const CB_recordingData = 1;
+const CB_startRecorderCompleted = 2;
+const CB_pauseRecorderCompleted = 3;
+const CB_resumeRecorderCompleted = 4;
+const CB_stopRecorderCompleted = 5;
+const CB_openRecorderCompleted = 6;
+const CB_closeRecorderCompleted = 7;
+const CB_recorder_log = 8;
+
+class FlutterSoundRecorder {
+        static newInstance(aCallback, callbackTable) { return new FlutterSoundRecorder(aCallback, callbackTable); }
+
+        constructor(aCallback, callbackTable) {
+                this.callback = aCallback;
+                this.callbackTable = callbackTable;
+                this.subscriptionDuration = 0;
+                this.timerId = null;
+                this.deltaTime = 0;
+                this.currentRecordPath = '';
+                this.localObjects = [];
+                this.instanceNo = instanceNumber;
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'Instance Number : ' + this.instanceNo.toString())
+                ++instanceNumber;
+        }
+
+
+
+        initializeFlautoRecorder(focus, category, mode, audioFlags, device) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'initializeFlautoRecorder');
+                this.callbackTable[CB_openRecorderCompleted](this.callback, IS_RECORDER_STOPPED, true);
+
+        }
+
+
+        deleteObjects() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> deleteObjects ');
+                for (var url in this.localObjects) {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'deleteRecord : ' + url);
+                        this.deleteRecord(url);
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- deleteObjects ');
+        }
+
+
+        releaseFlautoRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> releaseFlautoRecorder');
+                this.stop();
+                this.deleteObjects();
+                this.localObjects = [];
+
+                this.callbackTable[CB_closeRecorderCompleted](this.callback, IS_RECORDER_STOPPED, true);
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- releaseFlautoRecorder');
+        }
+
+
+        setAudioFocus(focus, category, mode, audioFlags, device) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'setAudioFocus');
+        }
+
+
+        isEncoderSupported(codec) {
+                /*
+                                for (var i in mime_types)
+                                {
+                                }
+                */
+                var r = MediaRecorder.isTypeSupported(mime_types[codec]);
+                if (r)
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'mime_types[codec] encoder is supported');
+                else
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'mime_types[codec] encoder is NOT supported');
+                return r;
+        }
+
+
+        setSubscriptionDuration(duration) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'setSubscriptionDuration');
+                this.subscriptionDuration = duration;
+                if (this.mediaRecorder != null)
+                        this.startTimer();
+        }
+
+
+        _deleteRecord(aPath,) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'deleteRecord: ' + aPath);
+                if ((aPath == null) || (aPath == '')) {
+                        path = lasturl;
+                } else {
+                        var path = aPath;
+                }
+                var myStorage;
+                if (path.substring(0, 1) == '/') {
+                        myStorage = window.localStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'localStorage');
+                } else {
+                        myStorage = window.sessionStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'sessionStorage');
+                }
+                var oldUrl = myStorage.getItem(path);
+                if (oldUrl != null && oldUrl != '') {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'Deleting object  : ' + oldUrl.toString());
+                        URL.revokeObjectURL(oldUrl);
+                        return true;
+                }
+
+                return false;
+        }
+
+
+
+        deleteRecord(path) {
+                this._deleteRecord(path);
+
+                var found = this.localObjects.findIndex(element => element == path);
+                if (found != null && found >= 0) {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, "Found : " + found);
+                        this.localObjects[found] = null;
+                }
+
+        }
+
+        setRecordURL(aPath, newUrl) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'setRecordUrl: ' + aPath + ' <- ' + newUrl);
+                var path = aPath;
+                var myStorage;
+                if ((path == null) || (path == '')) {
+                        return null;
+                }
+                if (path.substring(0, 1) == '/') {
+                        myStorage = window.localStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'localStorage');
+                } else {
+                        myStorage = window.sessionStorage;
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'sessionStorage');
+                }
+                var oldUrl = myStorage.getItem(path);
+                if (oldUrl != null && oldUrl != '') {
+                        this.callbackTable[CB_recorder_log](this.callback, DBG, 'Deleting object ' + ' : ' + oldUrl.toString());
+                        URL.revokeObjectURL(oldUrl);
+                } else {
+
+                }
+
+                lastUrl = aPath;
+
+                myStorage.setItem(path, newUrl);
+                this.callbackTable[CB_recorder_log](this.callback, DBG, '<--- setRecordURL ( ' + path + ' ) : ' + newUrl);
+
+        }
+
+        getRecordURL(aPath,) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, '---> getRecordURL : ' + aPath);
+                var r = getRecordURL(aPath);
+                if (r == null)
+                        r = ''; // stopRecorder does not like a null
+                this.callbackTable[CB_recorder_log](this.callback, DBG, '<--- getRecordURL :' + r);
+                return r;
+        }
+
+
+        async startRecorder(path, sampleRate, numChannels, bitRate, codec, toStream, audioSource) {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'startRecorder');
+                var me = this;
+                this.currentRecordPath = path;
+                var chunks = [];
+                var mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
+                me.mediaStream = mediaStream;
+                var options =
+                {
+                        audioBitsPerSecond: 160000,
+                        mimeType: mime_types[codec]
+                }
+                me.audioCtx = new AudioContext();
+                var mediaRecorder = new MediaRecorder(mediaStream,options);
+                me.mediaRecorder = mediaRecorder;
+                if (toStream) // not yet implemented !
+                        mediaRecorder.start(30); // 30 milliseconds for a chunk
+                else
+                        mediaRecorder.start();
+                me.callbackTable[CB_recorder_log](me.callback, DBG, "recorder started : " + mediaRecorder.state);
+                mediaRecorder.ondataavailable = function (e) {
+                        if (e.data) {
+                                if (toStream) // not yet implemented !
+                                {
+                                        me.callbackTable[CB_recordingData](me.callback, e.data);
+
+                                }
+                                if (path != null && path != '') {
+                                        me.callbackTable[CB_recorder_log](me.callback, DBG, 'On data available : ' + e.data.constructor.name);
+                                        const fileReader = new FileReader();
+                                        fileReader.onload = function() {
+                                          // 读取完成后的回调函数
+                                          const audioContext = new AudioContext();
+                                          audioContext.decodeAudioData(fileReader.result, function(audioBuffer) {
+                                                chunks.push(audioBuffer);
+                                                var dataBuffer = [];
+                                                var audioBufferData = audioBuffer.getChannelData(0);
+                                                const data = new Float32Array(audioBufferData);
+                                                const out = new Int16Array(audioBufferData.length);
+                                                for (let i = 0; i < data.length; i++) {
+                                                        const s = Math.max(-1, Math.min(1, data[i]));
+                                                        out[i] = (s < 0 ? s * 0x8000 : s * 0x7FFF);
+                                                }
+                                                this.samplesMono = out;
+                                                this.maxSamples = 1152;
+                                                let remaining = this.samplesMono.length;
+                                              
+                                                var mp3Encoder = new lamejs.Mp3Encoder(1,44100,128);
+                                                for (let i = 0; remaining >= 0; i += this.maxSamples) {
+                                                  const left = this.samplesMono.subarray(i, i + this.maxSamples);
+                                                  const mp3buffer = mp3Encoder.encodeBuffer(left);
+                                                  dataBuffer.push(new Int8Array(mp3buffer));
+                                                  remaining -= this.maxSamples;
+                                                }
+                                                var blob = new Blob(dataBuffer, { type: 'audio/mp3' });
+                                                var url = URL.createObjectURL(blob);
+                                                me.callbackTable[CB_recorder_log](me.callback, DBG, 'Instance Number : ' + me.instanceNo.toString())
+                                                me.setRecordURL(path, url);
+                                                var found = me.localObjects.findIndex(element => element == path);
+                                                if (found != null && found >= 0) {
+                                                        me.callbackTable[CB_recorder_log](me.callback, DBG, "Found : " + found);
+                                                        me.localObjects[found] = path;
+                                                } else {
+                                                        me.callbackTable[CB_recorder_log](me.callback, DBG, "NOT FOUND! : " + path);
+                                                        me.localObjects.push(path);
+                                                }
+                                                chunks = null;///[];
+                                                me.callbackTable[CB_recorder_log](me.callback, DBG, 'recorder stopped');
+                                                me.mediaRecorder = null;
+                                                me.callbackTable[CB_stopRecorderCompleted](me.callback, IS_RECORDER_STOPPED, true, me.getRecordURL(path));
+                                                me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onstop');
+                                          });
+                                        }
+                                        fileReader.readAsArrayBuffer(e.data);
+                                }
+                        }
+                }
+
+                mediaRecorder.onstart = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder OnStart');
+                        me.deltaTime = 0;
+                        me.startTimer();
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<---mediaRecorder OnStart : ' + me.mediaRecorder.state);
+                        me.callbackTable[CB_startRecorderCompleted](me.callback, IS_RECORDER_RECORDING, true);
+
+                }
+
+                mediaRecorder.onerror = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, "mediaRecorder OnError : " + e.error);
+                        me.stopRecorder()
+                }
+
+                mediaRecorder.onpause = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder onpause');
+                        me.callbackTable[CB_pauseRecorderCompleted](me.callback, IS_RECORDER_PAUSED, true);
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onpause');
+                }
+
+                mediaRecorder.onresume = function (e) {
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder onresume');
+                        me.callbackTable[CB_resumeRecorderCompleted](me.callback, IS_RECORDER_RECORDING, true);
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onresume');
+                }
+
+                mediaRecorder.onstop = async function (e) {
+                       
+                        me.callbackTable[CB_recorder_log](me.callback, DBG, '---> mediaRecorder onstop');
+                        var blob = new Blob(chunks, { 'type': mime_types[codec] });
+                        //const audioContext = new AudioContext();
+                        // var reader = new FileReader();
+                        // reader.onload = async function() 
+                        // {
+                        //         var buf = new Uint8Array(this.result);
+                        //         const audioBuffer = await audioContext.decodeAudioData(buf.buffer);
+                        //         // Import the lamejs library
+                        //         var audioBufferData = audioBuffer.getChannelData(0);
+                        //         const data = new Float32Array(audioBufferData);
+                        //         const out = new Int16Array(audioBufferData.length);
+                        //         for (let i = 0; i < data.length; i++) {
+                        //                 const s = Math.max(-1, Math.min(1, data[i]));
+                        //                 out[i] = (s < 0 ? s * 0x8000 : s * 0x7FFF);
+                        //         }
+                        //         this.samplesMono = out;
+                        //         this.maxSamples = 1152;
+                        //         let remaining = this.samplesMono.length;
+                              
+                        //         var mp3Encoder = new lamejs.Mp3Encoder(1,44100,128);
+                        //         for (let i = 0; remaining >= 0; i += this.maxSamples) {
+                        //           const left = this.samplesMono.subarray(i, i + this.maxSamples);
+                        //           const mp3buffer = mp3Encoder.encodeBuffer(left);
+                        //           this.dataBuffer.push(mp3buffer);
+                        //           remaining -= this.maxSamples;
+                        //         }
+                        //         blob = new Blob(this.dataBuffer, { type: 'audio/mp3' });
+                        // };
+                        // reader.readAsArrayBuffer(blob);
+                        var url = URL.createObjectURL(blob);
+                        //me.callbackTable[CB_recorder_log](me.callback, DBG, 'Instance Number : ' + me.instanceNo.toString())
+
+                        me.setRecordURL(path, url);
+
+                        // var found = me.localObjects.findIndex(element => element == path);
+                        // if (found != null && found >= 0) {
+                        //         me.callbackTable[CB_recorder_log](me.callback, DBG, "Found : " + found);
+                        //         me.localObjects[found] = path;
+                        // } else {
+                        //         me.callbackTable[CB_recorder_log](me.callback, DBG, "NOT FOUND! : " + path);
+                        //         me.localObjects.push(path);
+                        // }
+                        // chunks = null;///[];
+                        // me.callbackTable[CB_recorder_log](me.callback, DBG, 'recorder stopped');
+                        // me.mediaRecorder = null;
+                        // me.callbackTable[CB_stopRecorderCompleted](me.callback, IS_RECORDER_STOPPED, true, me.getRecordURL(path));
+                        // me.callbackTable[CB_recorder_log](me.callback, DBG, '<--- mediaRecorder onstop');
+                }
+                //});
+        }
+
+        stop() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> stop()');
+                this.stopTimer();
+                if (this.mediaRecorder != null) {
+                        this.mediaRecorder.stop();
+                        this.mediaRecorder = null;
+                }
+                if (this.mediaStream != null) {
+                        this.mediaStream.getTracks().forEach(track => track.stop());
+                        this.mediaStream = null;
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- stop()');
+        }
+
+        stopRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> stopRecorder');
+                this.stopTimer();
+                if (this.mediaRecorder != null) {
+                        this.mediaRecorder.stop();
+                } else {
+                        this.callbackTable[CB_stopRecorderCompleted](this.callback, IS_RECORDER_STOPPED, /*false*/true, this.getRecordURL(this.currentRecordPath));
+                }
+                this.mediaRecorder = null;
+
+                if (this.mediaStream != null) {
+                        this.mediaStream.getTracks().forEach(track => track.stop());
+                        this.mediaStream = null;
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, "JS:<--- stopRecorder");
+        }
+
+
+        pauseRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'pauseRecorder');
+                this.mediaRecorder.pause();
+                this.stopTimer();
+                this.callbackTable[CB_recorder_log](this.callback, DBG, "recorder paused : " + this.mediaRecorder.state);
+
+        }
+
+
+        resumeRecorder() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'resumeRecorder');
+                this.mediaRecorder.resume();
+                this.startTimer();
+                this.callbackTable[CB_recorder_log](this.callback, DBG, "recorder resumed : " + this.mediaRecorder.state);
+        }
+
+        startTimer() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'startTimer()');
+                this.stopTimer();
+                var me = this;
+
+                if (this.subscriptionDuration > 0) {
+                        this.countDownDate = new Date().getTime();
+                        this.timerId = setInterval
+                                (
+                                        function () {
+                                                var now = new Date().getTime();
+                                                var distance = now - me.countDownDate;
+                                                me.callbackTable[CB_updateRecorderProgress](me.callback, me.deltaTime + distance, 0);
+
+                                        },
+                                        this.subscriptionDuration
+                                );
+                }
+        }
+
+        stopTimer() {
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:---> stopTimer()');
+                if (this.timerId != null) {
+                        clearInterval(this.timerId);
+                        var now = new Date().getTime();
+                        var distance = now - this.countDownDate;
+                        this.deltaTime += distance;
+                        this.timerId = null;
+                }
+                this.callbackTable[CB_recorder_log](this.callback, DBG, 'JS:<--- stopTimer()');
+        }
+
+        
+}
+

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff