admin管理员组

文章数量:1401167

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?

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?

Share Improve this question asked Mar 23 at 7:38 AndrewAndrew 111 silver badge1 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 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/mp3/shotgun-reload-old_school-RA_The_Sun_God-580332022.mp3"></audio>

With Delay

const mp3 = new Audio("https://soundbible/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/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 });

本文标签: htmlAudio doesn’t stop playing using ltaudiogt tag in HTML5Stack Overflow