我在javascript中有一个类AudioClass
来播放音频,如下所示:(伪代码)
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。如何解决这个问题?
答案 0 :(得分:1)
您必须创建一个回调以在加载时播放音频。它可以在其他地方调用audio.play时工作,因为那时音频已加载。我建议你这样做:
var Audio = function() {
this.audioElement;
.
.
.
this.load = function(audioSource,callback) {
this.audioElement = //create Audio, set source etc.
this.audioElement.addEventListener("loadedmetadata", function(){
//some code
if(callback!=null)
callback();
});
}
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);
}
}
然后像这样使用它:
var audio = new Audio();
audio.load(audioSrc,function()
{
audio.play(20000);
});
对类似问题的回答显示了在开始使用之前如何预加载所有音频(如果您有其他音频): Proper onload for <audio>
答案 1 :(得分:0)
在注册loadeddata
或canplaythrough
元素的audio
事件的回调中播放声音。 (参见javascript audio onload和类似问题。)