gapless looping audio html5

Solution is to have 2 instances to control the play back.

Something like this :

var current_player = "a";
var player_a = document.createElement("audio");
var player_b = document.createElement("audio");

player_a.src = "sounds/back_music.ogg";
player_b.src = player_a.src;

function loopIt(){
    var player = null;

    if(current_player == "a"){
        player = player_b;
        current_player = "b";
    }
    else{
        player = player_a;
        current_player = "a";
    }

    player.play();

    setTimeout(loopIt, 5333); //5333 is the length of the audio clip in milliseconds.
}

loopIt();

And if you're using SoundManager2, source the audio through a Data URI instead of an URL request.

Strangely, I found that SoundManager2 request the file from the server each time it plays. Even it's loading from the cache, there will be a delay until the not-modified header is received for the audio file.


While still not perfect, this worked for me:

var audio_file = new Audio('whatever.mp3')
audio_file.addEventListener('timeupdate', function(){
    var buffer = .44
    if(this.currentTime > this.duration - buffer){
        this.currentTime = 0
        this.play()
    }
});

Experiment with the size of the buffer to find what works best for you