This commit is contained in:
Half-Shot
2024-12-05 11:24:42 +00:00
parent cc7ed79a90
commit 923b548f98

View File

@@ -24,21 +24,18 @@ type SoundDefinition = { mp3?: string; ogg: string };
* @param volume The volume to play at. * @param volume The volume to play at.
* @param ctx The context to play through. * @param ctx The context to play through.
* @param buffer The buffer to play. * @param buffer The buffer to play.
* @returns A promise that resolves when the sound has stopped playing.
*/ */
async function playSound( function playSound(
ctx: AudioContext, ctx: AudioContext,
buffer: AudioBuffer, buffer: AudioBuffer,
volume: number, volume: number,
): Promise<void> { ): void {
logger.debug("Playing back sound");
const gain = ctx.createGain(); const gain = ctx.createGain();
gain.gain.setValueAtTime(volume, 0); gain.gain.setValueAtTime(volume, 0);
const src = ctx.createBufferSource(); const src = ctx.createBufferSource();
src.buffer = buffer; src.buffer = buffer;
src.connect(gain).connect(ctx.destination); src.connect(gain).connect(ctx.destination);
src.start(); src.start();
return new Promise<void>((r) => src.addEventListener("ended", () => r()));
} }
/** /**
@@ -167,7 +164,11 @@ export function useAudioContext<S extends string>(
} }
return { return {
playSound: (name): void => { playSound: (name): void => {
playSound(audioContext, audioBuffers[name], effectSoundVolume); if (!audioBuffers[name]) {
logger.debug(`Tried to play a sound that wasn't buffered (${name})`);
return;
}
return playSound(audioContext, audioBuffers[name], effectSoundVolume);
}, },
}; };
} }