我如何控制音频 ScriptProcessor 函数的速率

问题描述

这是我的基本示例,我无法将其放入代码段中,因为它会生成安全错误。 问题是处理速率有点高,与我的需求相比,每个之间大约需要 300 到 500 毫秒。有没有办法控制它。 有没有办法暂停处理,直到麦克风收到输入。 感谢您的帮助。

显示费率的 html 输出

<input type='text' id='output' >

脚本:`

navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia ||
  navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
  navigator.getUserMedia({
      audio: true
    },function(stream) {
        output=document.getElementById("output");
        audioContext = new AudioContext();  
 
      
      analyser = audioContext.createAnalyser();
      microphone = audioContext.createmediastreamsource(stream);
      javascriptNode = audioContext.createscriptprocessor(256,1,1);

      analyser.smoothingTimeConstant = 0;// 0.8;
      analyser.fftSize = 32;//1024;
 
      microphone.connect(analyser);
      analyser.connect(javascriptNode);
      javascriptNode.connect(audioContext.destination);

      canvasContext = document.querySelector("#canvas").getContext("2d");

      javascriptNode.onaudioprocess = function() {
          var array = new Uint8Array(analyser.frequencyBinCount);
          analyser.getByteFrequencyData(array);
          var values = 0;

          var length = array.length;
          for (var i = 0; i < length; i++) {
            values += (array[i]);
          }

          var average = values / length;
          
          output.value= average;
         

        } // end fn stream
 
    },function(err) {
      console.log("The following error occured: " + err.name)
    });
} else {
  console.log("getUserMedia not supported");
}

我想要做的很简单。我所需要的只是在音频音量超过阈值时稍微滚动页面,如果您有更简单的替代方案,那就更好了。就像如何在 setTimeout 回调中访问卷一样。

解决方法

您创建的 ScriptProcessorNode 的缓冲区大小为 256。这意味着 onaudioprocess 事件每 256 帧调用一次,大约每 5 毫秒(44.1 kHz)调用一次。如果您需要大约 300 毫秒的时间,请使用 0.3 * 44100 或 16384,因为缓冲区大小是 2 的幂。

还要注意,您不需要调用分析器节点来获取数据。 onaudioprocess 函数已经具有在事件中传入的数据,您没有使用这些数据。

此外,根据您的用例,您可以完全摆脱脚本处理器,只使用分析器节点来获取您想要的数据。但随后您将需要 setTimeoutrequestAnimationFrame 来定期从分析器节点请求数据。