1

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?

1 Answer 1

1

You have an event listener that'll play twice:

  1. When the user clicks anywhere, the audio plays.

  2. When the user types anything, the audio plays.

Just remove both event listeners once it is called. In all three examples, click anywhere in the <iframe>. Once the mp3 is done, type something, and then click anywhere. There should be silence. If you only want the audio to play only once when the user clicks or hits a key, then the only code you need is in the first example below. The code in the question seems unnecessary unless you really want a delay, but that's really annoying for sound to pop off 1 minute after the page loads.

The three examples are as follows:

  1. Without Delay

    <audio> HTMLAudioElement
    .addEventListener()
    .removeEventListener()
    Third parameter: { once: true }

  2. With Delay

    Audio() constructor¹
    setTimeout()
    .addEventListener()
    .removeEventListener()
    option = { once: true }²

  3. With Delay Using Abort Controller

    Audio() constructor¹
    setTimeout()
    AbortController() constructor
    .addEventListener()
    Third parameter { signal: controller.signal }

    ¹ Alternative for <audio>
    ² Alternative for third parameter: { once: true }

Without Delay

const autoPlay = (e) => {
  const mp3 = document.querySelector("audio");
  mp3.play();
  window.removeEventListener('click', autoPlay, { once: true });
  window.removeEventListener('keydown', autoPlay, { once: true });
};

window.addEventListener('click', autoPlay, { once: true });
window.addEventListener('keydown', autoPlay, { once: true });
<audio src="https://soundbible.com/mp3/shotgun-reload-old_school-RA_The_Sun_God-580332022.mp3"></audio>

With Delay

const mp3 = new Audio("https://soundbible.com/mp3/shotgun-reload-old_school-RA_The_Sun_God-580332022.mp3");

let option = {
  once: true
};

const delay = () => {
  setTimeout(() => {
    mp3.play();
    window.removeEventListener('click', delay, option);
    window.removeEventListener('keydown', delay, option);
  }, 3000);
};

window.addEventListener('click', delay, option);
window.addEventListener('keydown', delay, option);

With Delay Using Abort Controller

const mp3 = new Audio("https://soundbible.com/mp3/shotgun-reload-old_school-RA_The_Sun_God-580332022.mp3");

const controller = new AbortController();

const delay = () => {
  setTimeout(() => {
    mp3.play();
    controller.abort();
  }, 3000);
};

window.addEventListener('click', delay, { signal: controller.signal });
window.addEventListener('keydown', delay, { signal: controller.signal });

Sign up to request clarification or add additional context in comments.

2 Comments

You're absolutely right that for a simple one-time trigger (on click or keypress), the minimal version of the code is sufficient and more efficient. However, in my case, the delay is intentional. I'm experimenting with how best to balance user control and timing. :)
I updated the answer with two more examples. Don't forget to accept this answer if it resolves your problem, happy coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.