From 7548e8e91cd0ec29591bf3236e84e2142a55153d Mon Sep 17 00:00:00 2001 From: Felix Chapman Date: Fri, 27 Sep 2024 19:32:19 +0100 Subject: [PATCH] Pause audio properly --- web/audio-processor.js | 13 +++++++++++-- web/audio.js | 11 +++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/web/audio-processor.js b/web/audio-processor.js index da8674d..835492b 100644 --- a/web/audio-processor.js +++ b/web/audio-processor.js @@ -3,8 +3,13 @@ class AudioProcessor extends AudioWorkletProcessor { super(); this.buffer = new CircularBuffer(2048); this.port.onmessage = event => { - for (const value of event.data) { - this.buffer.write(value); + if (event.data.type === "buffer") { + for (const value of event.data.buffer) { + this.buffer.write(value); + } + } else if (event.data.type === "mute") { + console.log("Muting"); + this.buffer.clear(); } } } @@ -24,6 +29,10 @@ class CircularBuffer { this.readCursor = 0; } + clear() { + this.buffer.fill(0); + } + write(value) { this.buffer[this.writeCursor] = value; this.writeCursor = (this.writeCursor + 1) % this.buffer.length; diff --git a/web/audio.js b/web/audio.js index 554b183..5e9ef49 100644 --- a/web/audio.js +++ b/web/audio.js @@ -15,17 +15,20 @@ async function startAudio() { addEventListener("click", startAudio); addEventListener("keydown", startAudio); addEventListener("visibilitychange", () => { - if (audioProcessorNode && document.visibilityState !== 'visible') { - audioProcessorNode.port.postMessage(new Float32Array(BUFFER_SIZE)) + if (audioProcessorNode && document.visibilityState === 'hidden') { + audioProcessorNode.port.postMessage({ type: "mute" }); } }); export function pushAudioBuffer(byte) { - if (audioProcessorNode == null || document.visibilityState !== 'visible') return; + if (audioProcessorNode == null) return; buffer[bufferIndex] = (byte / 255) - 0.5; bufferIndex += 1; if (bufferIndex === BUFFER_SIZE) { bufferIndex = 0; - audioProcessorNode.port.postMessage(buffer); + + // Silence audio when page isn't visible + const event = document.visibilityState === 'visible' ? { type: "buffer", buffer } : { type: "mute" }; + audioProcessorNode.port.postMessage(event); } }