Reputation: 2494
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?
P.S. 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.
Upvotes: 0
Views: 3402
Reputation: 109
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"))
Upvotes: 0
Reputation: 35253
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:
Upvotes: 3
Reputation: 5207
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.
Upvotes: 0