Skip to content

Commit

Permalink
use AudioContext.currentTime + DECAY_TIME to debounce sound start
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mzgoddard committed Jun 21, 2018
1 parent 331f083 commit 2126761
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/GreenPlayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand All @@ -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;
Expand Down Expand Up @@ -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');
}
Expand All @@ -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');
}
Expand All @@ -243,7 +246,7 @@ class SoundPlayer extends EventEmitter {
this.outputNode.stop();

this.isPlaying = false;
this.isStarting = null;
this.startingUntil = 0;

this.emit('stop');
}
Expand Down

0 comments on commit 2126761

Please sign in to comment.