export default class AudioController { constructor(audioId, options = {}) { this.audio = document.getElementById(audioId); this.audio.src = options.source; this.audio.volume = options.volume; this.audio.loop = true; this.isPlaying = false; this.isChangingSource = false; this.previousSource = null; } play() { if (this.isPlaying) { return; } if (this.isChangingSource) { return; } if (this.audio) { setTimeout(() => { this.isPlaying = true; this.audio.play().catch((error) => { this.isPlaying = false; this.changeSource(this.previousSource); }); }, 200); } } pause() { this.audio.pause(); this.isPlaying = false; } changeSource(newSource) { if (this.isChangingSource) { return; } if (this.audio) { this.isChangingSource = true; this.pause(); this.previousSource = this.audio.src; this.audio.src = newSource; this.isChangingSource = false; this.play(); } } changeVolume(newVolume) { const clampedVolume = Math.max(0, Math.min(1, newVolume)); this.audio.volume = clampedVolume; this.changeStateByVolume(); } changeStateByVolume() { const currentVolume = this.audio.volume; if (currentVolume > 0 && !this.isPlaying) { this.play(); } else if (currentVolume <= 0 && this.isPlaying) { this.pause(); } } changeOptions(newOptions) { const newSource = newOptions.source; const newVolume = newOptions.volume; this.changeSource(newSource); this.changeVolume(newVolume); } }