js可視化音頻

 var canvas = document.createElement("canvas");
    canvas.width = 100;
    canvas.height = 180;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "red";
    ctx.strokeStyle = "blue";
    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 = "1.mp3";
        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);

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章