1

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。如何解决这个问题?

4

2 回答 2

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>

于 2013-01-24T16:24:43.000 回答
0

在注册到元素事件loadeddata甚至更好的回调中播放声音。(请参阅javascript audio onload和类似问题。)canplaythroughaudio

于 2013-01-24T16:26:26.520 回答