0

I tried to make Audio Wave Visualization through this Post

Play a moving waveform for wav audio file in html

HERE IS CODE

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Audio Visualizer</title>
        <script type="text/javascript" src="visualization.js"></script>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <audio id="audioElement" src="bensound-perception.mp3"></audio>
        <canvas id="wave"></canvas>
        <div>
          <button onclick="audioElement.play()">Play the Audio</button>
          <button onclick="audioElement.pause()">Pause the Audio</button>
          <button onclick="audioElement.volume+=0.1">Increase Volume</button>
          <button onclick="audioElement.volume-=0.1">Decrease Volume</button>
        </div>

        <figure>
            <figcaption>Listen to the Track:</figcaption>
            <audio
                controls
                src="bensound-perception.mp3">
                    Your browser does not support the
                    <code>audio</code> element.
            </audio>
        </figure>
    </body>
</html>

HERE IS JS CODE

audioElement = document.getElementById('audioElement');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = audioCtx.createMediaElementSource(audioElement);
var analyser = audioCtx.createAnalyser();

// Bind our analyser to the media element source.
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);

//Get frequency data (800 = max frequency)
var frequencyData = new Uint8Array(400);
//Use below to show all frequencies
//var frequencyData = new Uint8Array(analyser.frequencyBinCount);

//Create canvas
var canvas = document.getElementById("wave");
canvas.style.width = "1000px";
canvas.style.height = "100px";

//High dpi stuff
canvas.width = parseInt(canvas.style.width) * 2;
canvas.height = parseInt(canvas.style.height) * 2;

//Get canvas context
var ctx = canvas.getContext("2d");

//Set stroke color to yellow
ctx.strokeStyle = "#ffff00";

//Draw twice as thick lines due to high dpi scaling
ctx.lineWidth = 2;

//Save x and y from the previous drawing
var drawX = 0;
var drawY = 0;

//Total duration (Seconds)
var duration;

//The animation reference
var animation;

//Audio is loaded
audioElement.oncanplaythrough = function() {

    //Get duration
    duration = audioElement.duration;

    //On play
    audioElement.onplay = function() {
        //Start drawing
        drawWave();
    };

    //On pause
    audioElement.onpause = function() {
        //Stop drawing
        cancelAnimationFrame(animation);
    };

    //On ended
    audioElement.onended = function() {
        //Stop drawing
        cancelAnimationFrame(animation);

        //Clear previous drawing
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        //Clear previous x and y values
        drawX = 0;
        drawY = 0;

        //Prevent audio from looping (you can remove this if you want it to loop)
        audioElement.pause();
    };
};

//Our drawing method
function drawWave() {

    //Current time (seconds)
    var currentTime = audioElement.currentTime;

    // Copy frequency data to frequencyData array.
    analyser.getByteFrequencyData(frequencyData);

    //Total loudness of all frequencies in frequencyData
    var totalLoudness = 0;
    for(var i = 0; i < frequencyData.length; i++) {
        totalLoudness += frequencyData[i];
    }

    //Average loudness of all frequencies in frequencyData
    var averageLoudness = totalLoudness / frequencyData.length;

    //Get the previous x axis value
    var previousDrawX = drawX;

    //Scale of progress in song (from 0 to 1)
    drawX =  currentTime / duration;
    //Multiply with canvas width to get x axis value
    drawX *= canvas.width;

    //Get the previous y axis value
    var previousDrawY = drawY;

    //Scale of average loudness from (0 to 1), frequency loudness scale is (0 to 255)
    drawY = averageLoudness / 255;
    //Multiply with canvas height to get scale from (0 to canvas height)
    drawY *= canvas.height;
    //Since a canvas y axis is inverted from a normal y axis we have to flip it to get a normal y axis value
    drawY = canvas.height - drawY;

    //Draw line
    ctx.beginPath();
    ctx.moveTo(previousDrawX, previousDrawY);
    ctx.lineTo(drawX, drawY);
    ctx.stroke();

    //Animate
    animation = requestAnimationFrame(drawWave);
}

HERE IS CSS

figure {
    margin: 0;
}

But it doesn't work for me, and shows Some Errors on Console also on Page it only Shows Buttons but not Audio Visualization and Audio works perfectly thats why i used figure block to test it.....

Please see the Screenshots i attached.

Console Error and Output

I also Tried other Posts already discussed on Stackoverflow but didn't found any relevent and easy like above one.

If anyone can help me with this then i would be Thankful.

Thanks in Advance

gautam
  • 96
  • 1
  • 14
  • 2
    Please add your code. It makes it easier for us to see what might be wrong. Looking at the error, it could be that you try to play your audio before you're DOM is fully loaded, but it's a bit guessing now... – N.P. Sep 11 '19 at 15:15
  • I just edited my post now – gautam Sep 12 '19 at 11:01
  • Add all your javascript code in a onload event: $(window).on("load", function(){ /*your code here */}); – N.P. Sep 12 '19 at 14:53
  • Now the Error is : The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. and when i click on Play new error occured: MediaElementAudioSource outputs zeroes due to CORS access restrictions for file:///Users/keikss/Projects/audio-visual/bensound-perception.mp3 – gautam Sep 13 '19 at 08:50
  • The audiocontext error is a new policy: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio . For the CORS, this post might help: https://stackoverflow.com/questions/31083704/mediaelementaudiosource-outputs-zeroes-due-to-cors-access-restrictions/37806272 – N.P. Sep 13 '19 at 12:56

1 Answers1

0

The error indicates that your JS code cannot find the <audio /> element. Make sure you have this element on the page and you reference it in document.getElementById(...) using the actual element's ID.

Eugene G
  • 244
  • 1
  • 4
  • You still have the same issue, put your js file at the end of the document before closing `body` tag. – Eugene G Sep 13 '19 at 16:52
  • already tried that one..also used console comments tag to check whether my js works or not, and comment section works properly.. – gautam Sep 17 '19 at 06:54