想要播放音频,它应该在Html和javascript中10秒后停止

want to play audio and it should be stop after 10 seconds inHtml and javascript?

本文关键字:javascript 10秒 Html 音频 播放      更新时间:2023-09-26

我是Html5和javascript的新手,当我打开html页面时,我想播放音频片段,10秒后应该停止,并显示音频播放成功的消息。

用于html5中的简单音频播放,如下

<!DOCTYPE html>
<html>
<body>

<audio controls>
  <source src="kill_bill.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script>
setInterval(function(), 10000);
$.each($('audio'), function () { this.stop(); alert('Audio Stop Successfully'); });

</script>
</body>
</html>

setTimeout似乎更合适:

var audio = document.createElement("audio");
audio.src = "sound.mp3";
audio.addEventListener("canplaythrough", function () {
        setTimeout(function(){
            audio.pause();
            alert("Audio Stop Successfully");
        },
        10000);
}, false); 

示例

在JS加载定时器/计数器到10秒时调用下面的函数。

计时器setInterval(Call Below Function, 10000)

停止音频$.each($('audio'), function () { this.stop(); alert('Audio Stop Successfully'); });

试试这个:::

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>TIMER</title>  
</head>
<body>

<audio id="aud" controls autoplay>
  <source src="test.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<script type="text/javascript">
 var myaud = document.getElementById("aud");
 var k = setInterval("pauseAud()", 10000);
 function playAud() {
     myaud.play();
 }
 function pauseAud() {
     myaud.pause();
     alert('Audio Stop Successfully');
     clearInterval(k); 
 } 
</script> 
</body>
</html>

首先,请注意:自动播放在iOS下不起作用;因为苹果阻止了这一切的发生。

至于停止音频,我总是建议使用mediaelement库,它支持非HTML5浏览器,并且有一个完整的界面来启动/停止音频播放。

<audio id="audio_killbill" muted controls onload="audiofor_10sec()">
    <source src="kill_bill.mp3.mp3"></source>  <!-- Webkit Browser -->
    <source src="kill_bill.mp3.ogg"></source>  <!-- Mozilla/Firefox -->
    Your browser isn't invited for super fun <code>audio</code> time.
</audio>

香草JS

function audiofor_10sec(){
     let audio = getElementById('audio_killbill');
     audio.muted = false; // New browser rule doesn't lets audio play automatically
     audio.play();         
     setTimeout(() => {
            audio.pause();
            audio.currentTime = 0; // Works as audio stop
     }, 10000);
 }