blob: 5e4c68af752300c9fa71c2da870bba75e2e0803b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
export type Sounds = Record<Sound, AudioBuffer>
export enum Sound {
Bass,
Snare,
HitHatClosed,
}
export function all(): Array<Sound> {
return [Sound.HitHatClosed, Sound.Snare, Sound.Bass]
}
const audioContext = new AudioContext()
let lazy: undefined | Sounds = undefined
export async function load(): Promise<Sounds> {
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')
])
lazy = {
[Sound.Bass]: bass,
[Sound.Snare]: snare,
[Sound.HitHatClosed]: hitHatClosed
}
return lazy
}
}
async function fetchSound(name: string): Promise<AudioBuffer> {
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[sound]
source.connect(audioContext.destination)
source.start()
}
|