使用jQuery在setInterval之后不重置音频元素卷

时间:2017-06-25 17:26:15

标签: javascript jquery audio setinterval

下面的代码随机选择和播放音频元素(由用户选择的不同音高)。我正在研究淡入淡出的选择;用户指定以秒为单位的淡入淡出时间,由ID(fade.value)传递。

我实际上有两个问题: A)在第一次迭代中,音频元素在开始播放之前开始淡化。 B)当重复调用相同的元素时,如果淡入淡出时间长于重复时间,则音量不会正确重置(这是tone.volume=1的预期点),但是"保持不变。 #34;

function pickAndPlay(pitchSet, saturation){
    var pitchCheck = rand(1,100);
    if (pitchCheck <= saturation){
        fyshuffle (pitchSet); // the Fischer-Yates shuffle
        var tone = document.getElementById(pitchSet[0]);
        tone.currentTime = 0;
        tone.volume = 1;
        tone.play();
        if(fadeTime.value>0){
            $(tone).animate({volume: 0}, fadeTime.value*1000);

        };
        document.getElementById("noteName").value=pitchSet[0];
        console.log(iteration);
        iteration++;
        console.log("tone.volume:"+tone.volume);
    };
};
function nextThing(millis,pitchSet,saturation){  
    if(iteration==0){pickAndPlay(pitchSet,saturation)};
    return setInterval(pickAndPlay,millis,pitchSet,saturation);  // this needs `return`: https://stackoverflow.com/questions/44609995/settimeout-recursion-javascript
};

感谢您提供有关如何解决这些问题的任何建议或参考。

1 个答案:

答案 0 :(得分:0)

对于第二个问题,当音频再次开始播放时,动画仍在运行。只需使用jQuery stop方法:

function pickAndPlay(pitchSet, saturation){
    var pitchCheck = rand(1,100);
    if (pitchCheck <= saturation){
        fyshuffle (pitchSet);
        var tone = document.getElementById(pitchSet[0]);
        tone.currentTime = 0;
        $(tone).stop();
        tone.volume = 1;
        tone.play();
        if(fadeTime.value>0){
            $(tone).animate({volume: 0}, fadeTime.value*1000); console.log(fadeTime.value);
        };
        document.getElementById("noteName").value=pitchSet[0];
        iteration++;
    };
};