如何在JavaScript中多次获得重复播放功能的声音?

时间:2019-07-03 13:22:34

标签: 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>

这时候代码只重复声音一次。

我很乐意为此提供一些建议/解决方案。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用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> 

与上述代码类似,仅供参考See W3 Schools Audio Loop