Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 634
Abhishek Mishra Avatar asked Oct 29 '10 15:10

Abhishek Mishra


People also ask

Can multiple audio sources can be played in HTML?

The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one.

Does audio element allow multiple source elements?

C - An audio element allows multiple source elements and browser will use the first recognized format.


2 Answers

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.

like image 169
robertc Avatar answered Sep 19 '22 13:09

robertc


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); 
like image 29
bobince Avatar answered Sep 23 '22 13:09

bobince