首页 > 解决方案 > JS:使用 setInterval 有条件地播放声音

问题描述

我有一个数组,里面有 16 个假布尔值。

var arr = [];
for(let i=0;i<15;i++){
    arr.push(false);
}

我将布尔值 [0] [4] [8] [12] 设置为 true。

arr[0]=true;
arr[4]=true;
arr[8]=true;
arr[12]=true;

我还有一个函数 playSound,它使用 WebAudio API 创建和播放声音。

function playSound(){
var oscillator = audio.createOscillator();

oscillator.type = 'sine';
oscillator.frequency.value = 440;
oscillator.connect(audio.destination);
oscillator.start(audio.currentTime);
oscillator.stop(audio.currentTime+0.5);
}

我希望我的“播放”函数每 500 毫秒检查一次数组的给定索引是否为真,如果是,则使用 playSound 函数播放声音。

var index = 0;

function play(){
    setInterval(function() {
    if(arr[index]===true){
        playSound;
        index++ % arr.length; ;
    }   
},500)}

但这似乎不起作用。怎么了?

标签: javascript

解决方案


var index = 0;

function play(){
    setInterval(function() {
    if(arr[index]===true){
        playSound();
        index++ ;
    }   
},500)}

我认为您忘记了()调用该方法的括号。


推荐阅读