MDN wants to talk to developers like you: https://qsurvey.mozilla.com/s3/a3e7b5301fea

AnalyserNode.getByteFrequencyData()

AnalyserNode接口的getByteFrequencyData()方法将当前频率数据复制到传入其中的Uint8Array(无符号字节数组)中。

如果数组的长度小于 AnalyserNode.frequencyBinCount, 那么Analyser多出的元素会被删除. 如果是大于, 那么数组多余的元素会被忽略.

语法

var audioCtx = new AudioContext();
var analyser = audioCtx.createAnalyser();
var dataArray = new Uint8Array(analyser.frequencyBinCount); // Uint8Array 的长度应该和 frequencyBinCount 相等
analyser.getByteFrequencyData(dataArray); // 调用 getByteFrequencyData 方法填充 Uint8Array 

返回值

一个 Uint8Array(无符号字节数组).

例子

下面的例子展示了 AudioContext 创建一个 AnalyserNode, 然后用 requestAnimationFrame<canvas> 去反复收集当前音频的频率数据, 并绘制为一个柱状风格的输出(频谱).

更多的例子/信息, 查看 Voice-change-O-matic 演示 (相关代码在 app.js 的 128行~205行).

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var analyser = audioCtx.createAnalyser();

  ...

analyser.fftSize = 256;
var bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
var dataArray = new Uint8Array(bufferLength);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteFrequencyData(dataArray);

  canvasCtx.fillStyle = 'rgb(0, 0, 0)';
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  var barWidth = (WIDTH / bufferLength) * 2.5;
  var barHeight;
  var x = 0;

  for(var i = 0; i < bufferLength; i++) {
    barHeight = dataArray[i];

    canvasCtx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)';
    canvasCtx.fillRect(x,HEIGHT-barHeight/2,barWidth,barHeight/2);

    x += barWidth + 1;
  }
};

draw();

参数

array (数组)
必须为Uint8Array, 频域数据将复制到该数组内.

规范

Specification Status Comment
Web Audio API
getByteFrequencyData()
Working Draft  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 10.0webkit 25.0 (25.0)  未实现 15.0webkit
22 (unprefixed)
6.0webkit
Feature Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? 26.0 1.2 ? ? ? 33.0

相关内容

文档标签和贡献者

 此页面的贡献者: WhiteMind, kylin_z
 最后编辑者: WhiteMind,