我AudioClass
在 javascript 中有一个类来播放音频,如下所示:(伪代码)
var AudioClass = function() {
this.audioElement;
.
.
.
this.load = function(audioSource) {
this.audioElement = //create Audio, set source etc.
this.audioElement.addEventListener("loadedmetadata", function(){
//some code
});
}
this.play = function(from, to) {
if(isNaN(this.audioElement.duration)) { return; } //line 1
this.audioElement.currentTime = from/1000; //line 2 //from & to in milliseconds
setTimeout(function() {
//pause audio.
}, to-from);
}
}
我正在使用Audio
如下:
/* the below lines are executed on document load. (playing background music) */
var audioInstance = new AudioClass();
audioInstance.load(audioSrc);
audioInstance.play(20000); //line 3 //20 seconds
/* the below line is used at other places whenever i need sound */
audioInstance.play(40000); //40 seconds
当我尝试在“第 3 行”播放音频时,有时音频没有加载,所以它正在抛出INVALID_STATE_ERR. DOM EXCEPTION 11 at line 2
. 当我检查音频持续时间时,它是NaN
. 所以我添加了“第 1 行”来检查是否持续时间,以便在加载音频之前isNaN()
它不会尝试设置。currentTime
这里的问题是有时音频的持续时间总是 NaN。如何解决这个问题?