简体   繁体   中英

Javascript object - force an event to fire

I am working on an audio playback system integrated in my web app. This is exactly what I need to do: create a sound file, establish the oncanplaythrough event, and then load the source URL. If the browser doesn't support mp3 files, trigger the oncanplaythrough event anyway (yes, even if the file doesn't load at all).

var sound = new Audio();
sound.addEventListener('canplaythrough', function(){
        alert('ready to play');
    }, false);
if(sound.canPlayType('audio/mp3')){
    sound.src = "myfile.mp3";
}
else{
    // force event to fire anyway
    sound.canplaythrough(); // doesn't work (this function is undefined)
    // sound.oncanplaythrough() is "null" if I try to use that
}

So ultimately, my only question is how can I force the event "canplaythrough" to fire in the Audio object?

PS if you're wondering, I am making an audio system for a game that loads all sound files one by one, and then initiates the level. The idea is to load files, or leave them empty if the browser doesn't support any of them. In any case, the event must fire for every single file added to the list, else it will be stuck waiting forever.

To manually fire an event you have to use the Event DOM APIs, they are not simply methods of elements. This might work (untested):

sound.dispatchEvent(new Event('canplaythrough'))

That method is called fireEvent in IE.

Here's the relevant documentation:

Are you trying to fire an customized event? If so, you can initial an event with event.initEvent and then use dispatchEvent to fire it.

You can use the dispachEvent function in most browsers like this:

sound.dispachEvent(new Event("canplaythrough"))

This is not completely cross-platform though so to take IE into account you must use fireEvent :

sound.fireEvent(new Event("canplaythrough"))

To put it all together you could use the following:

(sound.dispatchEvent||sound.fireEvent)(new Event("canplaythrough"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM