【问题标题】:Smooth volume change with Web Audio API使用 Web Audio API 平滑音量变化
【发布时间】:2020-05-22 01:23:05
【问题描述】:

javascript新手在这里。所以我一直在搞乱 Web Audio API 试图弄清楚事情,我发现exponentialRampToValueAtTime 只是我想要的,除了它似乎只做一次(?) 使用这个通用代码:

context = new AudioContext();
oscillator = context.createOscillator();
contextGain = context.createGain();
oscillator.type = 'sine';
oscillator.frequency = 440
oscillator.connect(contextGain);
contextGain.connect(context.destination);
oscillator.start(0);

contextGain.gain.value = 1 默认情况下,所以如果我运行contextGain.gain.exponentialRampToValueAtTime(0.1,context.currentTime + 2),它会从 1 平稳地下降到 0.1。但是如果我试图让它回到 1,比如contextGain.gain.exponentialRampToValueAtTime(1,context.currentTime + 2),它会突然跳到 1。为什么会发生这种情况?有什么方法可以让我想多少次就做多少次?提前致谢。

【问题讨论】:

    标签: javascript web-audio-api


    【解决方案1】:

    您需要先致电setValueAtTime() 来标记更改的开始:

    contextGain.gain.setValueAtTime(contextGain.gain.value, context.currentTime);
    contextGain.gain.exponentialRampToValueAtTime(0.1, context.currentTime + 2);
    

    没有这个,你的渐进式改变从过去开始。

    这是必需的,因为音频参数的逐渐变化是从上一个事件开始的。先前的事件是使用 setValueAtTime()linearRampToValueAtTime()exponentialRampToValueAtTime() 等方法的先前增益变化。

    引用自documentation at MDN

    AudioParam 接口的exponentialRampToValueAtTime() 方法安排AudioParam 值的逐渐指数变化。 更改从为上一个事件指定的时间开始,按照指数斜坡上升到value 参数中给定的新值,并在该时间达到新值在endTime 参数中给出。

    这是一个小演示:

    var context = new AudioContext();
    var oscillator = context.createOscillator();
    var gain = context.createGain();
    oscillator.type = 'sine';
    oscillator.frequency = 440
    oscillator.connect(gain);
    gain.connect(context.destination);
    
    document.getElementById('bplay').addEventListener('click', function() {
      context.resume();
      oscillator.start(0);
      gain.gain.setValueAtTime(0.01, context.currentTime);
      gain.gain.exponentialRampToValueAtTime(1, context.currentTime + 2);
    });
    
    document.getElementById('bdown').addEventListener('click', function() {
      gain.gain.cancelScheduledValues(context.currentTime);
      gain.gain.setValueAtTime(gain.gain.value, context.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.01, context.currentTime + 2);
    });
    
    document.getElementById('bup').addEventListener('click', function() {
      gain.gain.cancelScheduledValues(context.currentTime);
      gain.gain.setValueAtTime(gain.gain.value, context.currentTime);
      gain.gain.exponentialRampToValueAtTime(1, context.currentTime + 2);
    });
    <button type="button" id="bplay">Play</button>
    <button type="button" id="bdown">Volume down</button>
    <button type="button" id="bup">Volume up</button>

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2019-07-02
      • 2014-04-15
      相关资源
      最近更新 更多