gpt4 book ai didi

javascript - 如何创建一个JavaScript Audio Visualizer?

转载 作者:行者123 更新时间:2023-12-02 22:37:12 28 4
gpt4 key购买 nike

我一直在寻找一些解决方案,但并没有发现太多。我想要一些非常简单的东西,如下图所示。有没有人在项目中使用过一个?我可以使用任何建议或任何API?谢谢。

enter image description here

最佳答案

这是基础:

  • 您需要 Canvas
  • 您需要 Canvas 上下文
  • 您需要音频上下文


  • var canvas = document.createElement("canvas");
    canvas.width = 500;
    canvas.height = 180;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "black";
    ctx.strokeStyle = "white";
    ctx.lineCap = "round";
    var auctx;

    window.onload = () => {
    document.body.appendChild(canvas);
    auctx = new(window.AudioContext || window.webkitAudioContext)();
    startAudio();
    }

    var buffer, src, analyser, buffLen;
    var barWidth, dataArray;

    function startAudio() {
    var url = "https://cf-media.sndcdn.com/cTGZiRbnSouE.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vY1RHWmlSYm5Tb3VFLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE1MTk5NTQ5NjB9fX1dfQ__&Signature=JmNkAHzih0~f3lQVwvPXFeTIUVuMXbwlbqizsXbCtc6lFIxjRlqa3wUGp5-xAkt7AUlhiYxu~Wscc6MfQTTc527DHJURMpdqvdXv61ll-WJqoV1V-tpWSa~qR-NEAWGCGBvrge0BkRRAsOHFljeLNCvO3DjzH7lSTPMlV-MtbFV2k-PiY0vrY1LuicAOcfEtXYTiMBkg-rhzkeHFcNHYt2Nb2hmIvmWFI1cFG74FBIXTnVPAg2Yo0r-LeiirWvSgewkIu~zPzaVYjnPaN1y-ZGnPBFiBSC1mpVhtB5wkhTXF5LFthkGUHnUK2ybESr-1uOH9GLye-7dxdIXx~A1LDA__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ"; // nice url
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function() {
    auctx.decodeAudioData(request.response, function(buffer) {
    buffer = buffer;
    src = auctx.createBufferSource();
    src.buffer = buffer;
    src.loop = false;
    src.connect(auctx.destination);
    src.start(0);
    analyser = auctx.createAnalyser();
    src.connect(analyser);
    analyser.connect(auctx.destination);
    analyser.fftSize = 256;
    buffLen = analyser.frequencyBinCount;
    dataArray = new Uint8Array(buffLen);
    barWidth = (500 - 2 * buffLen - 4) / buffLen * 2.5;
    ctx.lineWidth = barWidth;
    draw();
    });
    }
    request.send();
    }

    function draw() {
    ctx.fillRect(0, 0, 500, 180);
    analyser.getByteFrequencyData(dataArray);
    for (var i = 0; i < buffLen; i++) {
    ctx.beginPath();
    ctx.moveTo(4 + 2 * i * barWidth + barWidth / 2, 178 - barWidth / 2);
    ctx.lineTo(4 + 2 * i * barWidth + barWidth / 2, 178 - dataArray[i] * 0.65 - barWidth / 2);
    ctx.stroke();

    }
    requestAnimationFrame(draw);
    }
    canvas {
    background: black;
    }


    此代码应该起作用。您可以添加一些图像和调整设置。

    关于javascript - 如何创建一个JavaScript Audio Visualizer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061023/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com