3

我是 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>
4

4 回答 4

4

一个 setTimeout 似乎更合适:

var audio = document.createElement("audio");
audio.src = "sound.mp3";

audio.addEventListener("canplaythrough", function () {
        setTimeout(function(){
            audio.pause();
            alert("Audio Stop Successfully");
        },
        10000);
}, false); 

例子

于 2013-05-03T11:44:46.647 回答
1

将计时器/计数器放在 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>
于 2013-05-03T09:28:21.787 回答
0

首先要注意:iOS下无法自动播放;因为苹果阻止它成为可能。

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

于 2013-05-03T09:24:33.077 回答
0
<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);
 }
于 2021-07-18T06:55:24.930 回答