javascript HTML5 音频 - 测试无效状态错误(或 Dom 异常 11)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12824487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 audio - testing for Invalid State Error ( Or Dom Exception 11 )
提问by Neablis
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.
我正在动态创建音频文件并动态更改源。但是,在我更改 src 并尝试更改 currentTime 后,我总是收到无效状态错误。你如何进行测试?或者最好在准备好时触发事件,然后调用 currentTime 来更改其音频位置。
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();
}
};
回答by Svish
For those coming after who actually need a testto prevent this invalid state error, you can try this:
对于那些真正需要测试以防止此无效状态错误的人,您可以尝试以下操作:
if(this.readyState > 0)
this.currentTime = aTime;
Seems to work for me anyways :)
无论如何似乎对我有用:)
回答by TimHayes
You are not passing a function referenceto 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:
您没有将函数引用传递给 addEventListener - 您正在调用内联函数。该doneLoading()函数立即执行(该文件已加载之前)和浏览器正确地抛出一个INVALID_STATE_ERR:
this.mAudioPlayer.addEventListener('canplaythrough', this.doneLoading(aTime), false );
this.mAudioPlayer.addEventListener('canplaythrough', this.doneLoading(aTime), false );
Try passing in a function referenceinstead. Like this:
尝试传入函数引用。像这样:
this.mAudioPlayer.addEventListener('loadedmetadata',function(){
this.currentTime = aTime / 1000.0;
}, false );