From 6571d1a72c1828d7c2ed902d07ec412110787bcf Mon Sep 17 00:00:00 2001 From: Joris Date: Sun, 19 Jun 2022 16:31:38 +0200 Subject: Add snare and hit hat closed sounds --- src/sounds.ts | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) (limited to 'src/sounds.ts') diff --git a/src/sounds.ts b/src/sounds.ts index 9ce8d2e..5e4c68a 100644 --- a/src/sounds.ts +++ b/src/sounds.ts @@ -1,5 +1,13 @@ -export interface Sounds { - kick: AudioBuffer +export type Sounds = Record + +export enum Sound { + Bass, + Snare, + HitHatClosed, +} + +export function all(): Array { + return [Sound.HitHatClosed, Sound.Snare, Sound.Bass] } const audioContext = new AudioContext() @@ -9,21 +17,30 @@ export async function load(): Promise { if (lazy !== undefined) { return lazy } else { + let [bass, snare, hitHatClosed] = await Promise.all([ + fetchSound('/sounds/bass.opus'), + fetchSound('/sounds/snare.opus'), + fetchSound('/sounds/hit-hat-closed.opus') + ]) - const kick = await fetch('/sounds/kick.opus') - .then(res => res.arrayBuffer()) - .then(ArrayBuffer => audioContext.decodeAudioData(ArrayBuffer)) - - lazy = { - kick + lazy = { + [Sound.Bass]: bass, + [Sound.Snare]: snare, + [Sound.HitHatClosed]: hitHatClosed } return lazy } } -export function playKick(sounds: Sounds) { +async function fetchSound(name: string): Promise { + return await fetch(name) + .then(res => res.arrayBuffer()) + .then(ArrayBuffer => audioContext.decodeAudioData(ArrayBuffer)) +} + +export function play(sounds: Sounds, sound: Sound): void { const source = audioContext.createBufferSource() - source.buffer = sounds.kick + source.buffer = sounds[sound] source.connect(audioContext.destination) source.start() } -- cgit v1.2.3