2017-06-25 39 views
0

以下代碼隨機選擇並播放由用戶選擇的不同音高的音頻元素。我正在嘗試淡出選項;用戶指定以秒爲單位的淡入淡出時間,並通過ID(fade.value)傳入。使用jQuery設置setInterval後音頻元素音量不會重置

我實際上有兩個問題: A)在第一次迭代中,音頻元素在開始播放之前開始淡化。 B)當重複調用同一元素時,如果漸變時間長於重複時間,則音量不能正確重置(這是tone.volume=1的預期點),但「保持關閉」。

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 
}; 

感謝您提供有關如何解決這些問題的任何建議或參考。

回答

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++; 
    }; 
};