Spaces:
Running
Running
// music_controller.js | |
class MusicController { | |
constructor() { | |
this.bgMusic = document.getElementById('bgMusic'); | |
this.musicToggle = document.getElementById('musicToggle'); | |
this.isMusicPlaying = false; | |
this.initializeMusic(); | |
this.setupEventListeners(); | |
} | |
initializeMusic() { | |
if (this.bgMusic) { | |
this.bgMusic.volume = 0.5; | |
} | |
} | |
setupEventListeners() { | |
// Setup toggle button click handler | |
this.musicToggle.addEventListener('click', () => this.toggleMusic()); | |
// Setup initial click handler for the whole document | |
document.addEventListener('click', () => { | |
if (!this.isMusicPlaying) { | |
this.playMusic().catch(error => console.log('Audio playback prevented:', error)); | |
} | |
}, { once: true }); | |
} | |
toggleMusic() { | |
if (this.isMusicPlaying) { | |
this.pauseMusic(); | |
} else { | |
this.playMusic(); | |
} | |
this.updateMusicIcon(); | |
this.isMusicPlaying = !this.isMusicPlaying; | |
} | |
playMusic() { | |
return this.bgMusic.play(); | |
} | |
pauseMusic() { | |
this.bgMusic.pause(); | |
} | |
updateMusicIcon() { | |
const icon = this.musicToggle.querySelector('.iconify'); | |
const iconName = this.isMusicPlaying ? 'mdi:speaker-off' : 'mdi:speaker'; | |
icon.setAttribute('data-icon', iconName); | |
} | |
} | |
// Initialize the music controller when the document is ready | |
document.addEventListener('DOMContentLoaded', () => { | |
const musicController = new MusicController(); | |
}); |