How can I add multiple sources to an HTML5 audio tag, programmatically?
Solution 1
Why add multiple files with JavaScript when you can just detect the types supported? I would suggest instead detecting the best type then just setting the src
.
var source= document.createElement('source');
if (audio.canPlayType('audio/mpeg;')) {
source.type= 'audio/mpeg';
source.src= 'audio/song.mp3';
} else {
source.type= 'audio/ogg';
source.src= 'audio/song.ogg';
}
audio.appendChild(source);
Add as many checks as you have file types.
Solution 2
You can use the same DOM methods as with any other element:
var source= document.createElement('source');
source.type= 'audio/ogg';
source.src= 'audio/song.ogg';
audio.appendChild(source);
source= document.createElement('source');
source.type= 'audio/mpeg';
source.src= 'audio/song.mp3';
audio.appendChild(source);
Abhishek Mishra
I run HeldFree Interactive, make things for iOS & Web. Previously, I worked on Menuscale Code - github.com/ideamonk Chirps - @ideamonk Blog - ideamonk.in
Updated on October 29, 2020Comments
-
Abhishek Mishra over 3 years
A lot of examples demonstrate multiple source tags nested in the audio tag, as a method to overcome codec compatibility across different browsers. Something like this -
<audio controls="controls"> <source src="song.ogg" type="audio/ogg" /> <source src="song.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio>
While with JavaScript, I'm also allowed to create an audio element like this -
var new_audio = document.createElement("audio");
Where I can set its source by the
.src
property -new_audio.src="....";
I failed to find how to add multiple sources in an audio element through JavaScript, something similar to source tags shown in the HTML snippet.
Do I manipulate the
new_audio
and add the<source...
tags inside it, just like one would manipulate any other DOM element? I'm doing this right now and it works, which is -new_audio.innerHTML = "<source src='audio/song.ogg' type='audio/ogg' />"; new_audio.play();
I wonder if there is a more appropriate way to do it?
-
Abhishek Mishra over 13 yearsI'm letting the user push in a list of alternate formats inside class attribute itself, making a simple to use plugin to help them create audio hovers. So I would not be aware of what types did end users provide. Thanks for the canPlayType tip, would be useful.
-
Andy West over 13 yearsJust something I noticed - you probably don't want to use the var keyword in your conditional. You're creating a new new_audio variable, and not referencing the existing one.
-
robertc over 13 years@AndyWest Yeah, it was also missing a bracket - pretty bad code all round :)
-
Andy West over 13 yearsNo big deal... +1 since I found it useful anyway.
-
bouncingHippo almost 12 yearsi tried doing <audio src="dropbox/link/ahc.mp3"> and it does work...any idea why?
-
justind over 10 yearsThis is a nice solution, but the post below better answers the original question.