I have this HTML code right now that automatically plays an audio after a set period of time:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Do You Remember?</title>
</head>
<body>
<!-- Audio element WITHOUT loop -->
<audio id="delayedAudio" preload="auto">
<source src="audio/eerie.mp3" type="audio/mpeg">
</audio>
<script>
const audio = document.getElementById('delayedAudio');
audio.loop = false; // extra safety
let started = false;
function allowAudioPlayback() {
if (started) return;
started = true;
setTimeout(() => {
// Explicitly reset and play once
audio.currentTime = 0;
audio.play().then(() => {
// Force stop after audio duration, in case it's misbehaving
setTimeout(() => {
audio.pause();
audio.currentTime = 0;
}, audio.duration * 1000 + 500); // Add buffer
}).catch(err => {
console.log('Autoplay blocked:', err);
});
}, 60000);
}
window.addEventListener('click', allowAudioPlayback, { once: true });
window.addEventListener('keydown', allowAudioPlayback, { once: true });
// Countdown
let timeLeft = 60;
const timer = document.getElementById("timer");
const countdown = setInterval(() => {
if (timeLeft > 0) {
timer.textContent = `Time left: ${timeLeft--}s`;
} else {
timer.textContent = "???";
clearInterval(countdown);
}
}, 1000);
However, for some reason, I cannot get the audio to stop playing once it starts. I don’t know how to solve this. Could someone please help?