How can I add multiple sources to an HTML5 audio tag, programmatically?

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.


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);