Search code examples
javascripthtmlfunctionaudiowav

Javascript playing an endless loop audio file without delay


Title is pretty much self explanatory.

I want to create an endless loop with JavaScript but without stopping between reading (again) the same exact file.

Here is my code:

function playMySong(url)
{
    var audio=document.createElement('audio');
    audio.style.display="none";
    audio.src=url;
    audio.autoplay=true;
    audio.onended=function()
    {
        playMySong('whiteNoise.wav');
    };
    document.body.appendChild(audio);
}

playMySong('whiteNoise.wav');

My code works (almost) perfectly but I want to get read of the tiny delay between the end of the sound to the beginning of the same exact file.

not it's:

[whiteNoise.wav][0.2ms delay][whiteNoise.wav]

I want:

[whiteNoise.wav][whiteNoise.wav]

:)


Solution

  • You are loading the audio file again and again when it reaches the end. Obviously, loading resources will take time.

    Why don't you use a simple loop attribute to the audio element? It will loop the audio clip itself without loading the resource again and again.

    function playMySong(url)
    {
        var audio=document.createElement('audio');
        audio.style.display="none";
        audio.src=url;
        audio.autoplay=true;
        audio.loop = true;
        document.body.appendChild(audio);
    }
    
    playMySong('whiteNoise.wav');