From e429f033fa88370d8367148ac19cce4874c01d2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20B=C3=A1ez?= Date: Mon, 2 Sep 2024 11:40:14 -0300 Subject: [PATCH] feat: add the ability of loadSound with AudioBuffer (#382) --- CHANGELOG.md | 1 + src/assets/sound.ts | 27 +++++++++++++++++++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb21e82e..6042b0ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -238,6 +238,7 @@ features of v4000, while v4000 will have the most features and breaking changes. ## Audio +- now you can pass an `AudioBuffer` to `loadSound()` (**v4000**) - added `loadMusic()` to load streaming audio (doesn't block in loading screen). (**v3001/4000**) diff --git a/src/assets/sound.ts b/src/assets/sound.ts index 27bc28ae..3b478d88 100644 --- a/src/assets/sound.ts +++ b/src/assets/sound.ts @@ -10,6 +10,10 @@ export class SoundData { this.buf = buf; } + static fromAudioBuffer(buf: AudioBuffer): SoundData { + return new SoundData(buf); + } + static fromArrayBuffer(buf: ArrayBuffer): Promise { return new Promise((resolve, reject) => audio.ctx.decodeAudioData(buf, resolve, reject) @@ -61,15 +65,22 @@ export function getSound(name: string): Asset | null { // load a sound to asset manager export function loadSound( name: string | null, - src: string | ArrayBuffer, + src: string | ArrayBuffer | AudioBuffer, ): Asset { - src = fixURL(src); - return assets.sounds.add( - name, - typeof src === "string" - ? SoundData.fromURL(src) - : SoundData.fromArrayBuffer(src), - ); + const fixedSrc = fixURL(src); + let sound: Promise | SoundData; + + if (typeof fixedSrc === "string") { + sound = SoundData.fromURL(fixedSrc); + } + else if (fixedSrc instanceof ArrayBuffer) { + sound = SoundData.fromArrayBuffer(fixedSrc); + } + else { + sound = Promise.resolve(SoundData.fromAudioBuffer(fixedSrc)); + } + + return assets.sounds.add(name, sound); } export function loadMusic(