I'm creating my audio element with new Audio()
, however when adding the event listener 'waiting'
, it triggers right away when I press play and does not actually trigger when it starts buffering.
Code:
var source = new Audio('some-url');
source.addEventListener('waiting', function () {
alert('Buffering');
};
source.play()
So 'waiting'
triggers right away, but it doesn't trigger again when audio starts buffering after playing, however it also triggers ONCE if I seek the track (even on localhost). How can I do this?
So for me this worked:
var source, sourceTime, dateTime;
source = new Audio('some-url');
function compare() {
var difference = Math.abs(sourceTime - dateTime);
if (difference > 1000) {
alert('buffering!');
}
};
source.addEventListener('timeupdate', function () {
var date, time;
date = new Date();
time = date.getTime();
sourceTime = date;
});
function updateTime() {
var date, time;
date = new Date();
time = date.getTime();
dateTime = time;
compare();
setTimeout(updateTime(), 50);
};
source.play()
updateTime();
The reason you need to check if difference is greater than 1000 is because timeupdate
event is inconsistent and might sometimes be exactly one second differ.