Kelompok02-Memory-Card/audioManager.js
2025-12-18 23:32:26 +07:00

61 lines
2.0 KiB
JavaScript

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() {
if(this.toggleBtn) this.toggleBtn.textContent = "🔊";
if(this.toggleBtn) {
this.toggleBtn.onclick = (e) => {
e.stopPropagation();
this.toggleMute();
};
}
if (this.sounds.bg) {
this.sounds.bg.volume = 0.5;
this.sounds.bg.play().catch(() => {
console.log("Autoplay ditahan browser, menunggu interaksi user...");
});
}
const unlockAudio = () => {
if (!this.isMuted && this.sounds.bg && this.sounds.bg.paused) {
this.sounds.bg.play().catch(() => {});
}
document.removeEventListener('click', unlockAudio);
};
document.addEventListener('click', unlockAudio);
},
toggleMute: function() {
this.isMuted = !this.isMuted;
if (this.isMuted) {
if(this.sounds.bg) this.sounds.bg.pause();
if(this.toggleBtn) this.toggleBtn.textContent = "🔇";
} else {
if(this.sounds.bg) this.sounds.bg.play().catch(() => {});
if(this.toggleBtn) this.toggleBtn.textContent = "🔊";
}
},
playSFX: function(name) {
if (this.isMuted) return;
const audio = this.sounds[name];
if (audio) {
audio.currentTime = 0;
audio.play().catch(() => {});
if (this.sounds.bg && this.sounds.bg.paused) {
this.sounds.bg.play().catch(() => {});
}
}
}
};
AudioManager.init();