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 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 });
本文标签: htmlAudio doesn’t stop playing using ltaudiogt tag in HTML5Stack Overflow
版权声明:本文标题:html - Audio doesn’t stop playing using <audio> tag in HTML5 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744294244a2599264.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论