使用带有实时输入的getFloatFrequencyData在Web音频中获取频率数据

时间:2016-10-27 23:40:29

标签: javascript audio html5-audio web-audio

工作示例:https://codepen.io/anon/pen/RGmVgG

我有代码工作,可以获取实时麦克风输入数据并将其输出到系统默认扬声器。我已经确认我收到了数据。

然后我试图获取频率数据,但它返回-Infinity数组(或Firefox中的-100)。

我已经通过了MDN文档并且似乎已经准备好了所有内容,但我没有获得频率数据。知道我需要做些什么不同吗?

HTML

Audio Data:
<div id="audio-data"></div>

Frequency Data:
<div id="frequency-data"></div>

JS

window.addEventListener('load', () => {
  navigator.mediaDevices.getUserMedia({audio: true})
    .then((stream) => {
      const audioDataDisplay = document.querySelector('#audio-data');
      const frequencyDataDisplay = document.querySelector('#frequency-data');
      const context = new AudioContext();
      const source = context.createMediaStreamSource(stream);
      const processor = context.createScriptProcessor(256, 1, 1);

      source.connect(processor);
      processor.connect(context.destination);

      // route default microphone audio to default speaker output for system
      // display live audio buffer data
      processor.onaudioprocess = (data) => {
        const channelCount = data.outputBuffer.numberOfChannels;

        for (let i = 0; i < channelCount; i++) {
          const inputChannelData = data.inputBuffer.getChannelData(i);
          const outputChannelData = data.outputBuffer.getChannelData(i);

          for (let j = 0; j < inputChannelData.length; j++) {
            outputChannelData[j] = inputChannelData[j];
          }

          audioDataDisplay.innerHTML = outputChannelData;
        }
      }

      // analyze the frequency data and display data
      // only shows as an array of -Infinity in Chrome, -100 in Firefox.
      const analyser = context.createAnalyser();
      const dataArray = new Float32Array(analyser.frequencyBinCount);

      setInterval(() => {
        analyser.getFloatFrequencyData(dataArray);
        frequencyDataDisplay.innerHTML = dataArray;
      }, 1000);
  });
});

1 个答案:

答案 0 :(得分:2)

您永远不会将任何内容连接到分析仪节点。添加类似

的内容
    source.connect(analyser);
创建分析器后