HTML5 audio - testing for Invalid State Error ( Or

2020-06-16 08:13发布

I am dynamically creating a audio file and changing the source on the fly. However after i change the src and try to change the currentTime i always get a Invalid state error. How do you go about testing for it? Or better fire a event when its ready and then calling currentTime to change its audio position.

this.doneLoading = function(aTime){

    try{
        this.mAudioPlayer.currentTime = aTime / 1000.0;
    }catch(err){
        console.log( err );
    }
    this.mAudioPlayer.play();   
}

this.playAtTime = function(aTime) {
    Debug("play at time audio: " + aTime);
    Debug("this.mAudioPlayer.currentTime: " + this.mAudioPlayer.currentTime);

     this.startTime = aTime;

    if (this.mAudioPlayer.src != this.mAudioSrc) {
        this.mAudioPlayer = new Audio();
        this.mAudioPlayer.src = this.mAudioSrc;
        this.mAudioPlayer.load();
        this.mAudioPlayer.play();
        this.mAudioPlayer.addEventListener('canplaythrough', this.doneLoading(aTime), false );
    }
    else if ((isChrome() || isMobileSafari()) && aTime == 0) {
        this.mAudioPlayer.load();
        this.mAudioPlayer.currentTime = aTime / 1000.0;
        this.mAudioPlayer.play();
        Debug("Reloading audio");
    }else{

        this.mAudioPlayer.currentTime = aTime / 1000.0;
        this.mAudioPlayer.play();
    }       



};

2条回答
贪生不怕死
2楼-- · 2020-06-16 09:04

You are not passing a function reference to your addEventListener - you are calling the function inline. The doneLoading() function executes immediately (before the file has loaded) and the browser correctly throws an INVALID_STATE_ERR:

this.mAudioPlayer.addEventListener('canplaythrough', this.doneLoading(aTime), false );

Try passing in a function reference instead. Like this:

this.mAudioPlayer.addEventListener('loadedmetadata',function(){
    this.currentTime = aTime / 1000.0;
}, false );
查看更多
狗以群分
3楼-- · 2020-06-16 09:06

For those coming after who actually need a test to prevent this invalid state error, you can try this:

if(this.readyState > 0)
    this.currentTime = aTime;

Seems to work for me anyways :)

查看更多
登录 后发表回答