HTML5 Audio events not triggering on Chrome

試著忘記壹切 提交于 2019-12-17 19:37:10

问题


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 other browsers. I also tried many other events such as oncanplay, oncanplaythrough, onloadedmetadata, etc. None of them trigger.

I think it might have to do with the caching. Tried looking around and there was some reports of this from 2-3 years ago but nothing recent.

Is there any other way I could detect if the audio is loaded, or make these events work?

EDIT: Here's a quick example: http://jsfiddle.net/3vxCu/1/ Works in opera and firefox, but not in Chrome. It should give an alert when sound if finished loading.


回答1:


It seems that the onloadeddata property does not work for some reason. But attaching an event handler through addEventListener (or via jQuery) works: http://jsfiddle.net/3vxCu/4/

bgSound = new Audio();
bgSound.src = "http://www.ehsankia.com/hawkthorne/audio/level.ogg";
bgSound.preload = "auto";
// Standard browsers (not IE before version 9):
// bgSound.addEventListener("loadeddata", testFunction, false);

// jQuery:
$(bgSound).on("loadeddata", testFunction);

function testFunction () {
    alert("Data loaded");
}



回答2:


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.



来源:https://stackoverflow.com/questions/10790091/html5-audio-events-not-triggering-on-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!