<audio id="music-player" src="/storage/files/music-1.mp3" loop></audio>
<script>
(function () {
const player = document.getElementById('music-player');
if (!player) return;
const toggle = document.getElementById('toggle-music');
if (screen.width < 1220) return;
if (!toggle) return;
let playing = false;
let firstPlay = true;
let iPos;
const KEY_MP_PAUSED = 'music-player-paused';
const KEY_MP_POSITION = 'music-player-position' + player.src;
const startPosition = parseFloat(localStorage.getItem(KEY_MP_POSITION));
const mpPaused = +localStorage.getItem(KEY_MP_PAUSED);
function enablePlay() {
if (firstPlay) {
firstPlay = false;
if (startPosition) player.currentTime = startPosition;
}
player.play();
toggle.classList.add('music-on');
}
function userClick() {
document.removeEventListener('click', userClick);
enablePlay();
}
if (!mpPaused) document.addEventListener('click', userClick);
function updateCurrentPosition() {
localStorage.setItem(KEY_MP_POSITION, player.currentTime.toString());
}
player.addEventListener('play', e => {
playing = true;
localStorage.setItem(KEY_MP_PAUSED, '0');
iPos = setInterval(updateCurrentPosition, 1000);
});
player.addEventListener('pause', e => {
playing = false;
localStorage.setItem(KEY_MP_PAUSED, '1');
clearInterval(iPos);
});
toggle.addEventListener('click', e => {
e.preventDefault();
e.stopPropagation();
document.removeEventListener('click', userClick);
if (playing) {
player.pause();
toggle.classList.remove('music-on');
} else {
enablePlay();
}
});
})();
</script>