[英]WEB Audio API Error: Cannot read Property 'getByteFrequencyData'
I am attempting to make an audio bar visualizer. 我正在尝试制作音频条可视化器。
Reading up on Web Audio API, I have the following code: 在阅读Web Audio API时,我有以下代码:
HTML: HTML:
<audio controls>
<source src="video/DownToEarth.mp3" type="audio/mp3">
</audio>
<canvas id="analyser_render"></canvas>
JAVASCRIPT: JAVASCRIPT:
var audioCtx, myAudio, canvas, ctx, source, analyser, bufferLength, dataArray, bars, bar_x, bar_width, bar_height;
window.addEventListener("load", initMp3Player, false);
function initMp3Player(){
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var myAudio = document.querySelector('audio');
var source = audioCtx.createMediaElementSource(myAudio);
var analyser = audioCtx.createAnalyser();
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
var canvas = document.getElementById('analyser_render');
ctx = canvas.getContext('2d');
source.connect(analyser);
analyser.connect(audioCtx.destination);
frameLooper();
}
function frameLooper(){
window.requestAnimationFrame(frameLooper);
analyser.getByteFrequencyData(dataArray);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#00CCFF';
bars = 100;
for (var i = 0; i < bars; i++) {
bar_x = i * 3;
bar_width = 2;
bar_height = -(dataArray[i] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
Now everything looks to be in order, but every time I try to run it I continue to get an error: Uncaught TypeError: Cannot read property 'getByteFrequencyData' of undefined I have data going INTO dataArray, but the getByteFrequencyData doesn't seem to be getting anything out of it. 现在一切看起来都井然有序,但是每次我尝试运行它时,我都会继续收到错误消息: 未捕获的TypeError:无法读取未定义的属性“ getByteFrequencyData”,我的数据将进入INTO dataArray,但是getByteFrequencyData似乎并没有从中得到任何东西。
I read from THIS POST that I might want to include some lines about the min and max decibel range, but that didn't make an ounce of difference, I am still receiving this error. 我从本帖子中了解到,我可能希望包括一些关于最小和最大分贝范围的行,但是并没有什么区别,我仍然收到此错误。
The variable analyser
does not exist in the scope you are trying to use it, as it is local to function initMp3Player
. 变量
analyser
在您要使用的范围内不存在,因为它在initMp3Player
函数中是本地的。
You need to change the signature of frameLooper
: 您需要更改
frameLooper
的签名:
function frameLooper(analyser){...
and when you call it, pass analyser
, which is in scope at the place that you call it from. 调用它时,请通过
analyser
,它位于调用它的位置的范围内 。
frameLooper(analyser);
so that it is available in your frameLooper
function. 以便在
frameLooper
函数中可用。
Alternatively, you could declare analyser
in a higher scope... but it's probably a good idea to avoid globals. 另外,您可以在更高范围内声明
analyser
...但是避免全局变量可能是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.