Skip to content

Commit

Permalink
Pause audio properly
Browse files Browse the repository at this point in the history
  • Loading branch information
aelred committed Sep 27, 2024
1 parent c3f00dd commit 7548e8e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
13 changes: 11 additions & 2 deletions web/audio-processor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
}
Expand All @@ -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;
Expand Down
11 changes: 7 additions & 4 deletions web/audio.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 7548e8e

Please sign in to comment.