diff --git a/audioManager.js b/audioManager.js new file mode 100644 index 0000000..8d65c68 --- /dev/null +++ b/audioManager.js @@ -0,0 +1,55 @@ +const AudioManager = { + isMuted: false, + sounds: { + bg: document.getElementById("bgMusic"), + click: document.getElementById("sfxClick"), + match: document.getElementById("sfxMatch"), + wrong: document.getElementById("sfxWrong"), + countdown: document.getElementById("sfxCountdown"), + win: document.getElementById("sfxWin"), + lose: document.getElementById("sfxLose") + }, + toggleBtn: document.getElementById("toggleMusic"), + + init: function() { + this.toggleBtn.textContent = "🔊"; + this.toggleBtn.onclick = (e) => { + e.stopPropagation(); + this.toggleMute(); + }; + if (this.sounds.bg) { + this.sounds.bg.volume = 0.5; + this.playMusic(); + } + }, + + toggleMute: function() { + this.isMuted = !this.isMuted; + if (this.isMuted) { + if(this.sounds.bg) this.sounds.bg.pause(); + this.toggleBtn.textContent = "🔇"; + } else { + this.playMusic(); + this.toggleBtn.textContent = "🔊"; + } + }, + + playMusic: function() { + if (!this.isMuted && this.sounds.bg) { + this.sounds.bg.play().catch(e => console.log("Autoplay waiting for interaction...")); + } + }, + + playSFX: function(type) { + if (this.isMuted) return; + const audio = this.sounds[type]; + if (audio) { + audio.currentTime = 0; + audio.play().catch(() => {}); + if (this.sounds.bg && this.sounds.bg.paused) { + this.playMusic(); + } + } + } +}; +AudioManager.init(); \ No newline at end of file