我有这个分析器(来自教程):
var playerE = document.getElementsByClassName('player')[0];;
var analyser = document.getElementById('analyzer');
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
window.addEventListener("load", playAnalyzer, false);
function playAnalyzer() {
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById('analyzer');
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(playerE);
source.connect(analyser);
analyser.connect(context.destination);
frameLooper();
}
function frameLooper() {
canvas.width = 800;
canvas.height = 400;
ctx.imageSmoothingEnabled = false;
window.requestAnimationFrame(frameLooper);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.fillStyle = "white"; // Color of the bars
bars = 700;
for (var i = 0; i < bars; i++) {
bar_x = i * 5;
bar_width = 3;
bar_height = -(fbc_array[i] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
现在它工作得非常好,我面临的唯一问题是频率。由于它根据每个频率添加条形,当条形宽度和间距大于1时,较高的频率会被忽略。如何将频率均匀分布到设置的条数(条= 700)?
除了频率音量之外,我还想知道如何增加2px的高度? (这样,当没有任何声音时,分析仪不会消失)
答案 0 :(得分:0)
我发现了自己,这里是怎么回事。
由于for循环考虑了每个频率,因此每个循环只需跳过4个小节。像这样:
for (var i = 0; i < bars; i += 4) /*<-- Adding 4 instead of 1*/ {
bar_x = i * 1;
bar_width = 3;
bar_height = -3 - (fbc_array[i] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
您必须调整条形数量,宽度和x。为了抵消条形图上的高度,只需从&#34; bar-height&#34;中减去任何值。如图所示。我在这个例子中减去了3个。
那就是它!