我是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>
答案 0 :(得分:3)
setTimeout似乎更合适:
var audio = document.createElement("audio");
audio.src = "sound.mp3";
audio.addEventListener("canplaythrough", function () {
setTimeout(function(){
audio.pause();
alert("Audio Stop Successfully");
},
10000);
}, false);
答案 1 :(得分: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>
答案 2 :(得分:0)
首先,注意:自动游戏在iOS下无法工作;因为Apple阻止它成为可能。
至于停止音频,我总是建议使用mediaelement库,它支持非HTML5浏览器,并有一个完整的界面来启动/停止音频播放。
答案 3 :(得分: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);
}