微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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 举报,一经查实,本站将立刻删除。