So I've used this questions answer as a basis of detecting whether or not an Audio object within my script is loading. Initially, the function worked perfectly, but I noticed that if I change the source of my Audio object while the it is playing, the buffering seems to always be set to true.

Here's what I have (JavaScript):

var _Player = {
    audio: null, buffering: false, lastPlayTime: 0,
    checkBuffering: function(){
        var buffer = setInterval(function(){
            var currentTime = this.audio.currentTime, offset = (100 - 20) / 1000;
            if(!this.buffering && currentTime < (this.lastPlayTime + offset) && !this.audio.paused){
                this.buffering = true;
                console.log("loading");
            }

            if(this.buffering && currentTime > (this.lastPlayTime + offset) && !this.audio.paused){
                this.buffering = false;
                console.log("not loading");
            }
            this.lastPlayTime = currentTime;
        }, 100);  
    },
    load: function(url){
        if(this.audio){
            this.audio.src = url;
        } else {
            this.audio = new Audio(url);
        }

        this.checkBuffering();
    }
};

and a quick HTML example:

<!-- when I click on this one, the output to console is correctly shown as 'true', then 'false' for the remainder of the output !-->
<button onclick="_Player.load(some_url);">Test 1</button>
<!-- but when I click this one afterwards, the output is basically swapped ('false' briefly, then 'true' for the remainder) !-->
<button onclick="_Player.load(some_other_url);">Test 2</button>

Don't know why this is occurring, but I feel as though it has something to do with it trying to check whether Audio sources are loading at once(?). All help is appreciated,
Cheers.

0 Answers