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.
This commit is contained in:
Michael "Z" Goddard 2018-06-21 13:44:41 -04:00
parent 331f083f5a
commit 2126761dc3
No known key found for this signature in database
GPG key ID: 762CD40DD5349872

View file

@ -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');
}