HTML5 Audio events not triggering on Chrome

前端 未结 2 1066
深忆病人
深忆病人 2020-12-10 09:02

I\'m trying to have a load progress bar in my game, and I have a function assigned to the onloadeddata attribute on my audio, but it is not triggering in Chrome. It works in

2条回答
  •  [愿得一人]
    2020-12-10 09:40

    If the attached jsfiddle is how you have implemented your code then I think I know what is wrong.

    Your jsfiddle shows:

    bgSound = document.createElement('audio');
    bgSound.src = "http://www.ehsankia.com/hawkthorne/audio/level.ogg";
    bgSound.onloadeddata = testFunction;
    
    function testFunction(){
        alert("Data loaded");
    }
    

    It should be like this:

    bgSound = document.createElement('audio');
    bgSound.onloadeddata = testFunction; // Event listener is attached _before_ loading the resource
    bgSound.src = "http://www.ehsankia.com/hawkthorne/audio/level.ogg";
    
    function testFunction(){
        alert("Data loaded");
    }
    

    Basically, you are attaching the event listener after the src is specified. Specifying the source should be the last thing you do since it sets everything in motion. Chrome is probably already past the point of calling listeners for that event by the time it is attached in your code.

提交回复
热议问题