// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // plays what client/sounds.ts decides on with web audio: a gain per category under master, and a panner for each // sound that comes from somewhere, fading linearly to nothing at its range import { SOUND_CATEGORIES, type SoundCategory } from "@/common/mod_data.ts"; import type { Position } from "@/common/mod_api/shared.ts"; import type { SoundFile, SoundOutput, Voice, VoiceSettings, Volumes } from "./sounds.ts"; export class WebAudioOutput implements SoundOutput { #context: AudioContext | undefined; #master: GainNode | undefined; #categories = new Map(); // decoded once, the first time anything plays them. by the bytes, so another server's files never mix in #buffers = new WeakMap>(); #volumes: Volumes | undefined; // browsers keep audio off until the player clicks or presses a key, so it starts then. the desktop app's web audio // (client/native/web_audio.ts) has no such rule and starts right away constructor(wait_for_input = true) { if (!wait_for_input) { this.#unlock(); return; } const unlock = () => { this.#unlock(); if (this.#context?.state === "running") { removeEventListener("pointerdown", unlock); removeEventListener("keydown", unlock); } }; addEventListener("pointerdown", unlock); addEventListener("keydown", unlock); } #unlock() { if (!this.#context) { const context = new AudioContext(); this.#master = context.createGain(); this.#master.connect(context.destination); for (const category of SOUND_CATEGORIES) { const gain = context.createGain(); gain.connect(this.#master); this.#categories.set(category, gain); } this.#context = context; if (this.#volumes) this.set_volumes(this.#volumes); } if (this.#context.state === "suspended") this.#context.resume(); } start(file: SoundFile, settings: VoiceSettings): Voice | undefined { const context = this.#context; // sounds played while it's suspended would all come at once when it resumes if (!context || context.state !== "running") return undefined; const out = settings.category ? this.#categories.get(settings.category)! : this.#master!; return new WebVoice(context, this.#buffer(context, file), out, settings); } #buffer(context: AudioContext, file: SoundFile) { let buffer = this.#buffers.get(file.bytes); if (!buffer) { // decoding detaches what it's given buffer = context.decodeAudioData(file.bytes.slice().buffer).catch((e) => { console.error(`couldn't decode the sound file ${file.id}:`, e); return undefined; }); this.#buffers.set(file.bytes, buffer); } return buffer; } listen(x: number, y: number, z: number, yaw: number, pitch: number) { const listener = this.#context?.listener; if (!listener) return; // the camera's forward and up, see ClientLevel's pick const forward = [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)]; const up = [Math.sin(yaw) * Math.sin(pitch), Math.cos(pitch), Math.cos(yaw) * Math.sin(pitch)]; // firefox only has the old setters if (listener.positionX) { listener.positionX.value = x; listener.positionY.value = y; listener.positionZ.value = z; listener.forwardX.value = forward[0]; listener.forwardY.value = forward[1]; listener.forwardZ.value = forward[2]; listener.upX.value = up[0]; listener.upY.value = up[1]; listener.upZ.value = up[2]; } else { listener.setPosition(x, y, z); listener.setOrientation(forward[0], forward[1], forward[2], up[0], up[1], up[2]); } } set_volumes(volumes: Volumes) { this.#volumes = volumes; if (!this.#master) return; this.#master.gain.value = volumes.master; for (const [category, gain] of this.#categories) gain.gain.value = volumes[category]; } } class WebVoice implements Voice { ended = false; #source: AudioBufferSourceNode | undefined; #gain: GainNode; #panner: PannerNode | undefined; #stopped = false; // set may come before the file is decoded #pitch: number; constructor( context: AudioContext, buffer: Promise, out: AudioNode, settings: VoiceSettings, ) { this.#pitch = settings.pitch; this.#gain = new GainNode(context, { gain: Math.min(1, settings.volume) }); if (settings.at) { this.#panner = new PannerNode(context, { panningModel: "HRTF", distanceModel: "linear", refDistance: 1, maxDistance: settings.range, positionX: settings.at.x, positionY: settings.at.y, positionZ: settings.at.z, }); this.#gain.connect(this.#panner).connect(out); } else { this.#gain.connect(out); } // the first time a file plays it starts once it's decoded buffer.then((buffer) => { if (!buffer || this.#stopped) { this.ended = true; return; } // played with an offset past its end, it would have finished already if (!settings.loop && settings.offset >= buffer.duration) { this.stop(); return; } const source = new AudioBufferSourceNode(context, { buffer, loop: settings.loop, playbackRate: this.#pitch, }); source.connect(this.#gain); source.onended = () => { this.ended = true; this.#disconnect(); }; source.start(0, settings.offset % buffer.duration); this.#source = source; }); } move(at: Position) { if (!this.#panner) return; this.#panner.positionX.value = at.x; this.#panner.positionY.value = at.y; this.#panner.positionZ.value = at.z; } set(volume: number, pitch: number, range: number) { this.#gain.gain.value = Math.min(1, volume); this.#pitch = pitch; if (this.#source) this.#source.playbackRate.value = pitch; if (this.#panner) this.#panner.maxDistance = range; } stop() { this.#stopped = true; this.ended = true; this.#source?.stop(); this.#disconnect(); } #disconnect() { this.#source?.disconnect(); this.#gain.disconnect(); this.#panner?.disconnect(); } }