Stop one finished sound from cutting off another (#34576)

Every sound played through a BackgroundAudio shares the one audio context,
which is suspended rather than closed when a sound ends so that it can be
reused. The handler suspended it whenever any source finished, so a sound
that started while an earlier one was still going was cut off part way
through. Suspending is not stopping either: the cut-off buffer stayed
where it was and picked up again the next time anything was played, which
is how a notification for one room ends up sounding in another.

The context is now suspended only once nothing this instance started is
still running, and each source is disconnected as it ends. A looping sound
holds the count up until it is stopped, and stopping it ends it, so the
context is still suspended as soon as everything is quiet.

Tests: the context is suspended when a lone sound ends, and left running
while a second sound outlasts the first.
This commit is contained in:
hayyaksi
2026-08-12 16:39:38 +03:00
committed by GitHub
parent 59561e615a
commit 8e6e5424bb
2 changed files with 88 additions and 1 deletions
@@ -0,0 +1,77 @@
/*
Copyright 2026 hayaksi1
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import { vi, describe, it, expect, beforeEach, type Mock } from "vitest";
import fetchMock from "@fetch-mock/vitest";
import { BackgroundAudio } from "./BackgroundAudio";
import { createAudioContext } from "./compat";
vi.mock("./compat", () => ({
createAudioContext: vi.fn(),
}));
describe("BackgroundAudio", () => {
let audioContext: {
createBufferSource: Mock;
decodeAudioData: Mock;
resume: Mock;
suspend: Mock;
destination: object;
};
/** The sources handed out by the mocked context, in the order they were created. */
let sources: Array<{ start: Mock; disconnect: Mock; onended?: () => void }>;
beforeEach(() => {
sources = [];
audioContext = {
createBufferSource: vi.fn().mockImplementation(() => {
const source = { start: vi.fn(), connect: vi.fn(), disconnect: vi.fn() };
sources.push(source);
return source;
}),
decodeAudioData: vi.fn().mockResolvedValue({}),
resume: vi.fn().mockResolvedValue(undefined),
suspend: vi.fn().mockResolvedValue(undefined),
destination: {},
};
vi.mocked(createAudioContext).mockReturnValue(audioContext as unknown as AudioContext);
// Every sound is fetched before it is decoded, and the decoding is mocked out above, so the
// bytes that come back never matter.
fetchMock.mockReset();
fetchMock.get("*", 200);
});
it("suspends the context once the sound has finished", async () => {
const audio = new BackgroundAudio();
await audio.play("sound.mp3");
expect(audioContext.suspend).not.toHaveBeenCalled();
sources[0].onended!();
expect(audioContext.suspend).toHaveBeenCalled();
});
it("keeps playing a sound that outlasts one started before it", async () => {
const audio = new BackgroundAudio();
await audio.play("first.mp3");
await audio.play("second.mp3");
// The first sound finishes while the second is still going.
sources[0].onended!();
expect(audioContext.suspend).not.toHaveBeenCalled();
sources[1].onended!();
expect(audioContext.suspend).toHaveBeenCalledTimes(1);
});
});
+11 -1
View File
@@ -18,6 +18,8 @@ const formatMap = {
export class BackgroundAudio {
private audioContext = createAudioContext();
private sounds: Record<string, AudioBuffer> = {};
/** How many sounds started here are still going. */
private playing = 0;
public async pickFormatAndPlay<F extends Array<keyof typeof formatMap>>(
urlPrefix: string,
@@ -50,8 +52,16 @@ export class BackgroundAudio {
source.connect(this.audioContext.destination);
await this.audioContext.resume();
this.playing++;
source.onended = () => {
this.audioContext.suspend();
source.disconnect();
this.playing--;
// Every sound played here shares the one context, which is suspended rather than closed so
// that it can be reused. Suspending it while another sound is still going would cut that
// one off mid-way and leave it to pick up again the next time anything is played.
if (this.playing === 0) {
this.audioContext.suspend();
}
};
source.start();