javascript - 如何在 JavaScript 中多次获得重复功能播放声音?
问题描述
我在使下面的脚本按预期工作时遇到了一些困难,即像函数(repeatR)一样重复播放声音。重复次数的输入可以来自用户(按钮)。
var timer, start;
function repeatR(callback, interval, repeats, immediate) {
var timer, trigger;
trigger = function() {
callback();
--repeats || clearInterval(timer);
};
interval = interval <= 0 ? 1000 : interval; // defaultní
repeats = parseInt(repeats, 10) || 0; // loop
timer = setInterval(trigger, interval);
if ( !! immediate) {
trigger();
}
return timer;
}
window.run = function () {
var args = Array.prototype.slice.call(arguments, 0);
if( timer ) { clearInterval(timer); }
start = (new Date).getTime();
document.getElementById("test").play();
}
<body>
<div>
<input type="button" value="Once after 1 sec" onclick="run(1000, 1)">
<input type="button" value="Once immediately" onclick="run(0, 1, true)">
<input type="button" value="5 times, 0.5s interval" onclick="run(500, 5)">
<input type="button" value="5 times, 0.5s interval, immediate start" onclick="run(500, 5, true)">
<input type="button" value="Forever, 1s interval" onclick="run(1000)">
<audio id="test" src="test.wav"</audio>
</div>
</body>
此时代码只重复一次声音。
我会很高兴对此提出一些建议/解决方案。
谢谢你。
解决方案
您可以使用 Audio loop 属性,它是audioObject.loop = true|false
<body>
<audio id="myAudio" controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio><br>
<button onclick="enableLoop()" type="button">Enable loop</button>
<button onclick="disableLoop()" type="button">Disable loop</button>
<button onclick="checkLoop()" type="button">Check loop status</button>
<script>
var x = document.getElementById("myAudio");
function enableLoop() {
x.loop = true;
x.load();
}
function disableLoop() {
x.loop = false;
x.load();
}
function checkLoop() {
alert(x.loop);
}
</script>
</body>
和上面的代码一样,供参考参见 W3 Schools Audio Loop