【问题标题】:WebAudio: Irregular behavior of setTargetAtTime?WebAudio:setTargetAtTime 的不规则行为?
【发布时间】:2017-10-25 13:00:31
【问题描述】:

下面的代码 (also live here) 似乎表明 setTargetAtTime 的性能不一致......它“应该”在 2 秒时膨胀到最大值,然后在 7 秒时淡入静默,然后在 12 秒时终止振荡器(安全安静足以避免"the ugly click"。)

相反,它会在 2 秒时膨胀到最大值,然后在 12 秒时开始一个尚未完成的淡入淡出,此时我们确实听到了难看的咔嗒声。

谁能解释为什么会这样?请注意,短值(注释为//0.3)足够快地丢弃它以避免点击。我已经在各种情况下尝试过这个,似乎(当无论如何淡入为 0 时)第三个参数随着值的上升而按比例延伸超出适当的停止时间。

<button id = "button" >
Start then stop oscillators
</button>

<script>
var audioContext = new AudioContext();
var fadeIn = 2;
var fadeOut = 5; //0.3
var gainNode = audioContext.createGain();
var osc = audioContext.createOscillator();
osc.type = "sine";
osc.frequency.value = 300;
osc.connect(gainNode);
gainNode.gain.value = 0;
gainNode.connect(audioContext.destination);

function startAndStop() {
    osc.start(audioContext.currentTime);
    gainNode.gain.setTargetAtTime(1, audioContext.currentTime, fadeIn);    
    gainNode.gain.setTargetAtTime(0, audioContext.currentTime + fadeIn, fadeOut);
    osc.stop(audioContext.currentTime + fadeIn + fadeOut + 5);
};

var button = document.getElementById("button");
button.addEventListener("click", startAndStop);

</script>

【问题讨论】:

标签: javascript web-audio-api


【解决方案1】:

setTargetAtTime 的第三个参数不是时间参数,所以不,它不应该在 2 秒时膨胀到最大值,然后在 7 秒时淡入静默,然后在 12 秒时终止振荡器 .

此参数设置值将更改的指数衰减率

所以值 5 会产生一个非常缓慢的衰减,非常慢以至于当你到达 t' 时它还没有结束。

计时应该在第二个参数中完成。

使用0.5 的固定衰减率修复您的代码会消除点击:

var audioContext = new AudioContext();

var fadeIn = 2;
var fadeOut = 5;

var gainNode = audioContext.createGain();
var osc = audioContext.createOscillator();
osc.type = "sine";
osc.frequency.value = 300;
osc.connect(gainNode);
gainNode.gain.value = 0;
gainNode.connect(audioContext.destination);

function startAndStop() {
  osc.start(audioContext.currentTime);
  gainNode.gain.setTargetAtTime(1, audioContext.currentTime + fadeIn, 0.5);
  gainNode.gain.setTargetAtTime(0, audioContext.currentTime + fadeOut, 0.5);
  osc.stop(audioContext.currentTime + fadeIn + fadeOut + 5);
};

var button = document.getElementById("button");
button.addEventListener("click", startAndStop);
<button id="button">
Start then stop oscillators
</button>

但实际上,您似乎想使用linearRampValueAtTime 而不是setTargetAtTime

【讨论】:

  • 是的!好的,太好了,这更有意义。第三个参数似乎“按比例伸展”,因为这正是它正在做的事情。下次我会记得检查 Moz 文档而不是我的参考/教程以了解函数的行为。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 2022-11-30
  • 2015-07-11
  • 1970-01-01
相关资源
最近更新 更多