Skip to content

Commit

Permalink
feat: add the ability of loadSound with AudioBuffer (#382)
Browse files Browse the repository at this point in the history
  • Loading branch information
lajbel authored Sep 2, 2024
1 parent 045ecaf commit e429f03
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**)

Expand Down
27 changes: 19 additions & 8 deletions src/assets/sound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export class SoundData {
this.buf = buf;
}

static fromAudioBuffer(buf: AudioBuffer): SoundData {
return new SoundData(buf);
}

static fromArrayBuffer(buf: ArrayBuffer): Promise<SoundData> {
return new Promise((resolve, reject) =>
audio.ctx.decodeAudioData(buf, resolve, reject)
Expand Down Expand Up @@ -61,15 +65,22 @@ export function getSound(name: string): Asset<SoundData> | null {
// load a sound to asset manager
export function loadSound(
name: string | null,
src: string | ArrayBuffer,
src: string | ArrayBuffer | AudioBuffer,
): Asset<SoundData> {
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> | 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(
Expand Down

0 comments on commit e429f03

Please sign in to comment.