[ACCEPTED]-How can I add multiple sources to an HTML5 audio tag, programmatically?-html5-audio

Accepted answer
Score: 45

Why add multiple files with JavaScript when 4 you can just detect the types supported? I 3 would suggest instead detecting the best 2 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 1 checks as you have file types.

Score: 28

You can use the same DOM methods as with 1 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);

More Related questions