Get "waves" from sound or music frequency

Asked

Viewed 8,570 times

23

How do I display the sound waves of any sound (music)? I don’t know if it is possible to get this with JS or some other language. Waves of this type:

ondas sonoras

An example is as Soundcloud does, displaying a kind of wave of audio being executed.

I want to store on my server/site, that is, having the audio locally and display to the visitor the frequency of the sound.

  • 1

    Dude, your doubt is too wide. How are you going to get that sound? How do you want to present these waves? Could you try specifying a little more?

  • 2

    I believe that there is no way to do this in the right way without having special hardware to capture the sound, if it is external. What normal programs do is detect the volume changes in the music and work with animations on top of this information by simulating the sound waves.

  • 1

    @Felipeavelar I edited in my description, thanks for the suggestion.

  • @Dirtyoldman you know the name of some program or equipment that performs this ?

  • @Dirtyoldman, in fact I imagine that he captures the frequency of each piece of music and generates the graphic (or animation) that he wants, no? An mp3 file, for example, contains enough information for this. That’s why I asked how it will receive this data...

  • Even, one of the options, is he already have the information of these animations ready and only send a json, for example, to handle on the front end, while the sound plays...

  • I have seen this done in other languages and always seemed to me very efficient, I believe that a hardware just for this is exaggeration, sorry to be honest @Dirtyoldman

Show 2 more comments

2 answers

25


To HTML5 Audio API 5 allows this type of visualization, with a lot of flexibility. Here is an adapted example of a tutorial from MDN, taking audio from an element <audio> and drawing the visualization in a <canvas>:

WARNING: The example below no longer works inline because it uses an audio file from another domain, causing a warning MediaElementAudioSource outputs Zeroes due to CORS access Restrictions in Chrome (and probably something similar in other browsers). If you test in your development environment or server, with local files, it works. Strangely, in the edit preview here site also works.

var canvas = document.querySelector('canvas');
var audio = document.querySelector('audio');
var audioCtx = new AudioContext();
var source = audioCtx.createMediaElementSource(audio);
var analyser = audioCtx.createAnalyser();
source.connect(analyser);
source.connect(audioCtx.destination);

// CORS
audio.crossOrigin = "anonymous";

analyser.fftSize = 1024;
var bufferLength = analyser.fftSize;
var dataArray = new Uint8Array(bufferLength);

var w = canvas.width;
var h = canvas.height;
var sliceWidth = w * 1.0 / bufferLength;
canvasCtx = canvas.getContext('2d');
canvasCtx.clearRect(0, 0, w, h);
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
    
function draw() {
    drawVisual = requestAnimationFrame(draw);
    analyser.getByteTimeDomainData(dataArray);

    canvasCtx.fillRect(0, 0, w, h);
    canvasCtx.beginPath();

    var x = 0;
    
    for(var i = 0; i < bufferLength; i++) {
        var v = dataArray[i] / 128.0;
        var y = v * h/2;
        if(i === 0) {
            canvasCtx.moveTo(x, y);
        } else {
            canvasCtx.lineTo(x, y);
        }
        x += sliceWidth;
    }
    canvasCtx.lineTo(canvas.width, canvas.height/2);
    canvasCtx.stroke();
};

draw();
<audio controls>
  Your browser does not support the <code>audio</code> element.
    <source src="//upload.wikimedia.org/wikipedia/commons/4/43/Goldberg_variations_1_start.ogg" type="audio/ogg" />
</audio>

<canvas width="600" height="150"></canvas>

Audio credit: Wikimedia Commons, initial excerpt from Bach’s Variation 1 Goldberg Variations, BWV 988

  • thanks a lot, you helped me a lot !! Congratulations. that’s exactly what I was looking for.

16

If the audio "wave" is static (no animation), you can use the Wavesurfer

Example:

@bfavaretto allow me to use the same audio as your? :)

var wavesurfer   = Object.create(WaveSurfer);
var pausePlayBtn = document.getElementById('playPause');
var stopBtn      = document.getElementById('stop');
var progress     = document.getElementById('progress');
var isPaused     = true;

wavesurfer.init({
    container: document.querySelector('#wave'),
    waveColor: 'violet',
    progressColor: 'purple'
});

wavesurfer.on('loading', function (status) {
    if (status === 100) {
        progress.innerHTML = "";
    } else {
        progress.innerHTML = status + "%";
    }
});

wavesurfer.on('ready', function () {
    isPaused = true;

    wavesurfer.play();
    pausePlayBtn.innerHTML = "Pause";

    pausePlayBtn.onclick = function() {
       isPaused = isPaused ? false : true;

       pausePlayBtn.innerHTML = isPaused ? "Pause" : "Play";
       wavesurfer.playPause();
    };
    
    stopBtn.onclick = function() {
       isPaused = false;
       pausePlayBtn.innerHTML = "Play";
       wavesurfer.stop();
    };
});

wavesurfer.load('https://upload.wikimedia.org/wikipedia/commons/4/43/Goldberg_variations_1_start.ogg');
<script src="//wavesurfer-js.org/dist/wavesurfer.min.js"></script>
<div id="wave">
    <p id="progress">0</p>
</div>
<button id="playPause">Play</button>
<button id="stop">Stop</button>

Audio credit: Wikimedia Commons, initial excerpt from Bach’s Variation 1 Goldberg Variations, BWV 988

  • 1

    @Guilhermenascimento vc tb helped me a lot. I have no words to thank you and the bfavaretto, thank you very much !!

  • 1

    William, his example broke, probably when Wikimedia changed the access policy (I edited mine a while ago for that; see my latest Edit). The wavesurfer allows setar audio.crossOrigin = "anonymous"; somewhere? That should solve.

  • @bfavaretto infelzimente the solution seems to have either server side, then I will see better.

  • Ué, now it looks like it’s working?! Must have been a temporary problem in some of the external files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.