Set html audio play/pause based on a cookie (works only on pause, but not on play)

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.

Codepen

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);

1 Like

Solved, turns out I just needed to use

if(isMuted=='true')

and then isMuted = 'false'; or isMuted = 'true';

Here is the updated pen

Works like a clock in Chrome with autoplay enabled! :slight_smile:

Safari is more strict with the autoplay, so I added a check and only run this code for Chrome, and run standard player for Safari

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

if(isSafari){ 
alert('Is safari');
//Do something

} else {
alert('Is other browser');
// Do something
}

If someone finds a workaround for autoplay in Safari, or if you need help with implementing it in Chrome please let me know!

1 Like