refactor: sound smoothing

This commit is contained in:
cha0s 2021-02-12 04:57:49 -06:00
parent de5b9360ae
commit 6a8e8f410e

View File

@ -11,6 +11,39 @@ const cache = new LRU({
maxAge: Infinity,
});
const MAX_INTERVAL = 125;
const queue = new Map();
const play = (audio, uri) => {
if (!queue.has(uri)) {
queue.set(uri, {audio, count: 0});
}
queue.set(uri, {audio, count: Math.min(4, queue.get(uri).count + 1)});
};
const pull = () => {
const it = queue.entries();
for (let current = it.next(); current.done !== true; current = it.next()) {
const {value: [uri, {audio, count}]} = current;
const clone = audio.cloneNode();
clone.volume = audio.volume;
clone.play();
if (1 === count) {
queue.delete(uri);
}
else {
queue.set(uri, {audio, count: count - 1});
}
}
const hmi = MAX_INTERVAL / 2;
setTimeout(pull, Math.max(20, hmi + hmi * (Math.random() - 0.5)));
};
if ('client' === process.env.SIDE) {
setTimeout(pull, MAX_INTERVAL);
}
export default () => class Sound extends JsonResource {
#audio;
@ -53,9 +86,9 @@ export default () => class Sound extends JsonResource {
}
play() {
const clone = this.#audio.cloneNode();
clone.volume = this.#audio.volume;
clone.play();
if ('client' === process.env.SIDE) {
play(this.#audio, this.uri);
}
}
};