如何在 Canvas 中制作双 JavaScript Audio Vizualizer?

问题描述

我曾经在 CodePan 上的 JavaScript 中发现了这样一个 Audio Visualizer,我在问如何使它加倍并以与所附照片相同的方式设置它

代码和完整代码链接CodePan

JavaScript Visualizer 绘制代码

_drawSpectrum: function(analyser) {
    var that = this,canvas = document.getElementById('canvas'),cwidth = canvas.width,cheight = canvas.height - 2,meterWidth = 10,//width of the meters in the spectrum
        gap = 2,//gap between meters
        capHeight = 2,capStyle = '#fff',meterNum = 255;//800 / (10 + 2),//count of the meters
        capYPositionArray = []; ////store the vertical position of hte caps for the preivous frame
    ctx = canvas.getContext('2d'),gradient = ctx.createLinearGradient(0,300);
    gradient.addColorStop(1,'#0f0');
    gradient.addColorStop(0.5,'#ff0');
    gradient.addColorStop(0,'#f00');
    var drawMeter = function() {
        var array = new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);
        if (that.status === 0) {
            //fix when some sounds end the value still not back to zero
            for (var i = array.length - 1; i >= 0; i--) {
                array[i] = 0;
            };
            allCapsReachBottom = true;
            for (var i = capYPositionArray.length - 1; i >= 0; i--) {
                allCapsReachBottom = allCapsReachBottom && (capYPositionArray[i] === 0);
            };
            if (allCapsReachBottom) {
                cancelAnimationFrame(that.animationId); //since the sound is stoped and animation finished,stop the requestAnimation to prevent potential memory leak,THIS IS VERY IMPORTANT!
                return;
            };
        };
        var step = Math.round(array.length / meterNum); //sample limited data from the total array
        ctx.clearRect(0,cwidth,cheight);
        for (var i = 0; i < meterNum; i++) {
            var value = array[i * step];
            if (capYPositionArray.length < Math.round(meterNum)) {
                capYPositionArray.push(value);
            };
            ctx.fillStyle = capStyle;
            //draw the cap,with transition effect
            if (value < capYPositionArray[i]) {
                ctx.fillRect(i * 12,cheight - (--capYPositionArray[i]),meterWidth,capHeight);
            } else {
                ctx.fillRect(i * 12,cheight - value,capHeight);
                capYPositionArray[i] = value;
            };
            ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
            ctx.fillRect(i * 12 /*meterWidth+gaP*/,cheight - value + capHeight,cheight); //the meter
        }
        that.animationId = requestAnimationFrame(drawMeter);
    }
    this.animationId = requestAnimationFrame(drawMeter);
}

对于图形质量很抱歉,但我几年前拍了一张照片/屏幕截图:/

Visualizer Screen

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)