Having the following example to add a file AudioTest_(1).mp3
to an html5 audio element , I want to additionally add the file in case there is no codec to play the first one.AudioTest_(1).ogg
var audioel = document.getElementById('audioElem');
if (audioel !== null) {
audioel.setAttribute('src', 'http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).mp3');
}
<audio id="audioElem" autoplay>
Your browser does not support the <code>audio</code> element.
</audio>
Normally you would have multiple items source
and the browser would automatically pick the first one that has the codecs to play it for, but I don't know if it's possible to do this using Javascript Only or if there is some other way to load the file than if it can be played from a list provided in execution time.
PS: Preferably not to use jQuery.
Thanks in advance.
Here are a couple of options made with JavaScript that change depending on who is in charge of the logic to decide which font to use:
Delegating the choice to the browser
As Leandro indicates in his answer, a quick option would be to add all the fonts inside the tag
audio
and let the browser take care of selecting the first one that works for it.So, if for example you have a list with the different audio sources you could do something like this:
Advantages of this method:
Disadvantages of this method:
Logic in the code
Another option would be to keep you in control of the code to know which of the fonts is actually being used. In this case, and assuming a list of sources with the previous example, the solution would be like this:
src
Then all you have to do is add a handler for the event
error
that takes care of selecting the next source in the list and replacing the current one.An example of this code would be:
Advantages of this method:
Disadvantages of this method:
I imagine that instead of assigning the src as an attribute you should assign it as a new element "source"
Cheers
Check out this fiddle to see how to switch video (and preload them if you want). It works the same for an HTML5 audio element.