AnalyserNode.getByteFrequencyData()

AnalyserNode 介面的 getByteFrequencyData() 方法會將當前的頻率資料複製到 Uint8Array (en-US) (無號 byte 陣列)。

如果陣列的元素數目比 AnalyserNode.frequencyBinCount (en-US) 少的話,多餘的元素會被 drop 掉。如果比需要的少的話,多餘的元素會被忽略。

語法

var audioCtx = new AudioContext();
var analyser = audioCtx.createAnalyser();
var dataArray = new Uint8Array(analyser.frequencyBinCount); // Uint8Array 應該要和 frequencyBinCount 等長
analyser.getByteFrequencyData(dataArray); // 將 getByteFrequencyData() 回傳的資料放進 Uint8Array

回傳值

Uint8Array (en-US)

範例

下面的範例顯示出 AudioContext (en-US) 用於建立一個 AnalyserNode 的基本用法,然後 requestAnimationFrame 以及 <canvas> 用來重複收集當前聲音輸入的頻率資料並在 "winamp bargraph style" 畫出輸出。若要知道更完整的範例或是資訊,請參考 Voice-change-O-matic demo (看 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();

參數

陣列
頻率定義域會被複製進去的 Uint8Array (en-US)

規範

規範 狀態 Comment
Web Audio API
The definition of 'getByteFrequencyData()' in that specification.
Recommendation  

瀏覽器支援度

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help! (en-US)
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 10.0webkit (en-US) 25.0 (25.0)  No support 15.0webkit (en-US)
22 (unprefixed)
6.0webkit (en-US)
Feature Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? 26.0 1.2 ? ? ? 33.0

參看