From 2126761dc368ce7aee6ef97c5eddcb31140f1791 Mon Sep 17 00:00:00 2001 From: "Michael \"Z\" Goddard" Date: Thu, 21 Jun 2018 13:44:41 -0400 Subject: [PATCH] use AudioContext.currentTime + DECAY_TIME to debounce sound start Debounce when the sound starts to keep from playing many copies of the same sound layered on itself. Use AudioEngine's currentTime in seconds plus some value in milliseconds to make sure the sound has a chance to start before starting a second playback. --- src/GreenPlayer.js | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/GreenPlayer.js b/src/GreenPlayer.js index 8e53252..e73954a 100644 --- a/src/GreenPlayer.js +++ b/src/GreenPlayer.js @@ -31,10 +31,18 @@ class SoundPlayer extends EventEmitter { this.initialized = false; this.isPlaying = false; - this.isStarting = null; + this.startingUntil = 0; this.playbackRate = 1; } + /** + * Is plaback currently starting? + * @type {boolean} + */ + get isStarting () { + return this.isPlaying && this.startingUntil > this.audioEngine.audioContext.currentTime; + } + /** * Handle any event we have told the output node to listen for. * @param {Event} event - dom event to handle @@ -147,7 +155,7 @@ class SoundPlayer extends EventEmitter { const taken = new SoundPlayer(this.audioEngine, this); taken.playbackRate = this.playbackRate; if (this.isPlaying) { - taken.isStarting = this.isStarting; + taken.startingUntil = this.startingUntil; taken.isPlaying = this.isPlaying; taken.initialize(); taken.outputNode.disconnect(); @@ -170,7 +178,7 @@ class SoundPlayer extends EventEmitter { } this.volumeEffect = null; this.initialized = false; - this.isStarting = null; + this.startingUntil = 0; this.isPlaying = false; return taken; @@ -205,12 +213,7 @@ class SoundPlayer extends EventEmitter { this.isPlaying = true; - const isStarting = this.isStarting = Promise.resolve() - .then(() => { - if (this.isStarting === isStarting) { - this.isStarting = null; - } - }); + this.startingUntil = this.audioEngine.audioContext.currentTime + this.audioEngine.DECAY_TIME; this.emit('play'); } @@ -227,7 +230,7 @@ class SoundPlayer extends EventEmitter { this.outputNode.stop(this.audioEngine.audioContext.currentTime + this.audioEngine.DECAY_TIME); this.isPlaying = false; - this.isStarting = null; + this.startingUntil = 0; this.emit('stop'); } @@ -243,7 +246,7 @@ class SoundPlayer extends EventEmitter { this.outputNode.stop(); this.isPlaying = false; - this.isStarting = null; + this.startingUntil = 0; this.emit('stop'); }