Skip to content

Commit

Permalink
fix annoying audiocontext start on page load, remove unused playSound…
Browse files Browse the repository at this point in the history
… (simplify)
  • Loading branch information
zardoy committed Sep 23, 2023
1 parent 52d2ea7 commit d210aca
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 32 deletions.
File renamed without changes.
41 changes: 9 additions & 32 deletions src/menus/components/button.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,15 @@
//@ts-check
const { LitElement, html, css, unsafeCSS } = require('lit')
const widgetsGui = require('minecraft-assets/minecraft-assets/data/1.17.1/gui/widgets.png')
const { options } = require('../../optionsStorage')

const audioContext = new window.AudioContext()
const sounds = {}
const { options, watchValue } = require('../../optionsStorage')

const buttonClickAudio = new Audio()
buttonClickAudio.src = 'button_click.mp3'
// load as many resources on page load as possible instead on demand as user can disable internet connection after he thinks the page is loaded
let loadingSounds = []
async function loadSound (path) {
loadingSounds.push(path)
const res = await window.fetch(path)
const data = await res.arrayBuffer()

sounds[path] = await audioContext.decodeAudioData(data)
loadingSounds.splice(loadingSounds.indexOf(path), 1)
}

export async function playSound (path) {
const volume = options.volume / 100

// todo?
if (loadingSounds.includes(path)) return
let soundBuffer = sounds[path]
if (!soundBuffer) throw new Error(`Sound ${path} not loaded`)

const gainNode = audioContext.createGain()
const source = audioContext.createBufferSource()
source.buffer = soundBuffer
source.connect(gainNode)
gainNode.connect(audioContext.destination)
gainNode.gain.value = volume
source.start(0)
}
buttonClickAudio.load()
watchValue(options, o => {
buttonClickAudio.volume = o.volume / 100
})

class Button extends LitElement {
static get styles () {
Expand Down Expand Up @@ -156,10 +134,9 @@ class Button extends LitElement {
}

onBtnClick (e) {
playSound('click_stereo.mp3')
buttonClickAudio.play()
this.dispatchEvent(new window.CustomEvent('pmui-click', { detail: e, }))
}
}

loadSound('click_stereo.mp3')
window.customElements.define('pmui-button', Button)

0 comments on commit d210aca

Please sign in to comment.