I’m trying to make background audio remember the play/pause state. I have achieved pausing it and storing the pause state in the cookie, so when I go between page one and two it stays paused (vs autoplaying initially on both pages), but when I click play after that and refresh the page, even though the cookie is changing to “false” in the inspector, the audio doesn’t play and the div colour doesn’t change to green.
Here is the code
External Scripts
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2.2.1/src/js.cookie.min.js"></script>
HTML
<div class="div" id="toggle"> PLAY/PAUSE </div>
<audio id="player" src="https://storage.yandexcloud.net/timcliss/About.mp3" autoplay loop>
CSS
.div {
background-color:green;
height: 50px;
color: white;
text-align: center;
}
JS
var audio = $('#player')[0];
audio.volume = 0.5;
var isMuted = Cookies.get('playerMuted'); // Receive stored cookie
if(isMuted) // If muted, stop the player
{
$('#player')[0].pause();
$('#toggle').css({'background-color': 'red'});
}
else
{
$('#player')[0].play();
$('#toggle').css({'background-color': 'green'});
}
// This function will be called when you click the toggle div
function toggleMute()
{
if(isMuted) // If player is muted, then unmute it
{
$('#player')[0].play();
$('#toggle').css({'background-color': 'green'});
isMuted = false;
} else // Else mute it
{
$('#player')[0].pause();
$('#toggle').css({'background-color': 'red'});
isMuted = true;
}
Cookies.set('playerMuted', isMuted); // Save current state of player
}
$('#toggle').click(toggleMute);