src/sounds.js 1.1 K raw
1
const AudioContext = window.AudioContext || window.webkitAudioContext
2
const audioContext = new AudioContext()
3
const soundNames = ['game-over', 'jump', 'level-up']
4
const soundBuffers = {}
5
let SOUNDS_LOADED = false
6
let muted = localStorage.getItem('dino-muted') === 'true'
7
8
loadSounds().catch(console.error)
9
export function playSound(name) {
10
  if (SOUNDS_LOADED && !muted) {
11
    audioContext.resume()
12
    playBuffer(soundBuffers[name])
13
  }
14
}
15
16
export function isMuted() {
17
  return muted
18
}
19
20
export function toggleMute() {
21
  muted = !muted
22
  localStorage.setItem('dino-muted', muted)
23
  return muted
24
}
25
26
async function loadSounds() {
27
  await Promise.all(
28
    soundNames.map(async (soundName) => {
29
      soundBuffers[soundName] = await loadBuffer(`/assets/${soundName}.mp3`)
30
    })
31
  )
32
33
  SOUNDS_LOADED = true
34
}
35
36
async function loadBuffer(filepath) {
37
  const response = await fetch(filepath)
38
  const arrayBuffer = await response.arrayBuffer()
39
  return audioContext.decodeAudioData(arrayBuffer)
40
}
41
42
function playBuffer(buffer) {
43
  const source = audioContext.createBufferSource()
44
45
  source.buffer = buffer
46
  source.connect(audioContext.destination)
47
  source.start()
48
}