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 badge1 Answer
Reset to default 1You have an event listener that'll play twice:
When the user clicks anywhere, the audio plays.
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:
Without Delay
<audio>
HTMLAudioElement
.addEventListener()
.removeEventListener()
Third parameter:{ once: true }
With Delay
Audio()
constructor¹
setTimeout()
.addEventListener()
.removeEventListener()
option = { once: true }
²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 });
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744294245a4567182.html
评论列表(0条)