gapless looping audio html5
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
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.
Unfortunately this is one of the weaknesses of the HTML5 element. There is no guarantee that audio will play when you want it to or without delay.
There are two options worth looking into:
-
SoundManager2 - a great library that would probably be helpful here, though it'll use Flash to play the audio in this case;
-
Web Audio API in Chrome or the Audio Data API in Firefox - both are really new, and not really ready for prime time yet, but allow you to do things like scheduled audio playback, looping and a whole lot more.