2

我是一名音频工程师,刚刚开始使用 JavaScript 和 HTML5,特别是 WEB 音频 API。

我有这个连接到目的地(输出)的振荡器代码。这是代码

我想要一个按钮来连接和断开振荡器到目的地我设法让它启动但我无法断开它。

<html>
<head>
    <script>
        //creating the context
        context = new webkitAudioContext(); //allways the first code for audio API
        function osc1(frequency){ // Creating a function that has an oscillator going to gainNode and then going to the destination

            //creating AudioNodes and AudioParams

            //creating OscillatorNode
            var oscillator = context.createOscillator(); //creating Node's as Variables
            oscillator.type = 0; //0 is a sine wave
            oscillator.noteOn(0); // turning on the oscillator
            oscillator.frequency.value = frequency;// telling that frequency in () of the function equals to what


            //creating GainNode
            var gain = context.createGainNode(); // creating the Gain node
            gain.gain.value = 1; // setting up the value for gain node


            //Making the connections
            oscillator.connect(gain); // connecting oscillator to gain
            gain.connect(context.destination); // connecting gain to destination (speakers)
        }; // now we have a function called osc1(we can put frequency in here) then we can re call


    </script>
</head>

<body>
    <input type="button" value="on"  onClick="osc1(500);" />

</body>

</html>

我知道断开它的代码是oscillator.disconnect();,但我不知道如何执行它。

4

3 回答 3

0

我也在做这个。

您执行振荡器.disconnect(0),其中零表示输出编号。

我认为这意味着如果您将振荡器分别连接到增益节点和滤波器节点,增益将为断开(0)而滤波器将断开(1)。

我认为跟踪什么输出是我们的工作,因为看起来不像是内置的方式。

我希望规范发生变化,以便我们可以将 disconnect() 传递给我们想要断开连接的实际节点。

于 2013-04-04T16:34:12.723 回答
0

已经提到过,但是您需要公开oscillator变量(可能在全局范围内),以便您的 off 函数可以断开它(确保您没有oscillator在处理程序中重新声明变量onclick)。

这是一个工作示例:http: //jsbin.com/iwetiy/1/edit

于 2013-04-04T20:37:54.287 回答
0

也许您想在函数外部声明振荡器变量:

var context = new webkitAudioContext();
var oscillator = context.createOscillator();
function osc1(frequency){
  var button = document.getElementsByTagName('input')[0];
  if (button.value === 'off') {
    button.value = 'on';
    oscillator.disconnect();
  } else {
    button.value = 'off';
    // same as your original code (connect, noteOn...)
于 2013-03-25T01:13:38.497 回答