added manager audio

This commit is contained in:
Nathan 2025-12-18 23:05:49 +07:00
parent 5b1817d846
commit bd6189c1ac

55
audioManager.js Normal file
View File

@ -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();