Javascript 网络音频API:如何使所有振荡器静音并暂停旋律

Javascript 网络音频API:如何使所有振荡器静音并暂停旋律,javascript,web,audio,web-audio-api,Javascript,Web,Audio,Web Audio Api,我为我弹奏的每个音符制作一个新的振荡器 function playSound(freq, duration) { var attack = 5, decay = duration, gain = context.createGain(), osc = context.createOscillator(); gain.connect(context.destination); gain.gain.setValueAt

我为我弹奏的每个音符制作一个新的振荡器

function playSound(freq, duration) { 
    var attack = 5,
        decay = duration,
        gain = context.createGain(), 
        osc = context.createOscillator(); 

    gain.connect(context.destination); 
    gain.gain.setValueAtTime(0, context.currentTime);
    gain.gain.linearRampToValueAtTime(0.1, context.currentTime + attack / 1000);
    gain.gain.linearRampToValueAtTime(0, context.currentTime + decay / 1000);

    osc.frequency.value = freq;
    osc.type = "sine";
    osc.connect(gain); 
    osc.start(0);

    setTimeout(function() { 
        osc.stop(0);
        osc.disconnect(gain);
        gain.disconnect(context.destination);
    }, decay)
}

旋律在for循环中播放,其中调用playSound。当我单击“暂停”按钮时,我希望使旋律静音并暂停for循环,这样,如果我再次单击“播放”按钮,旋律将恢复。如何访问所有当前振荡器以断开它们的连接?

在此代码中,您不能

1) 根据设计,Web Audio API中没有对节点图的内省—它支持优化垃圾收集,并针对大量节点进行优化。两种可能的解决方案-要么维护播放振荡器列表,要么将它们全部连接到单个增益节点(即,将其包络增益节点连接到“混音器”增益节点),然后断开(并释放对)该增益节点的引用

2) 不确定“暂停for循环”是什么意思-我想您在play note方法周围有一个for循环?

您可以查看音频上下文

const audioCtx=new AudioContext();
audioCtx.suspend();
audioCtx.resume();

值得注意的是,在web audio中,您不能暂停音频节点,但必须停止该节点,恢复时必须重新创建该节点。你可能已经知道了@cwilso下面的答案是正确的,您需要存储一个对以后要与之交互的任何节点的引用。