S.P. S.P. - 5 months ago 23
jQuery Question

play mp3 in tag audio by javascript

i've the following html:

<audio id="carteSoudCtrl">
<source src="http://soundjax.com/reddo/17350%5EClick02.mp3" type="audio/mpeg">
<source src="http://soundjax.com/reddo/90754%5EWINNER.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>


with this javascript:

$('#carteSoudCtrl')[1].play();


why is not working on chrome? i'm missing something? $('#carteSoudCtrl')[0].play(); is working.
thank you.

https://jsfiddle.net/o8mjvty5/

Answer

See the updated demo here Link

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

So all different files inside an <audio> tag must corresponding to same file in different format and browser will play the format which is most suitable to play.

If you need to play the second file we need to create second tag and then insert the <source src="http://soundjax.com/reddo/90754%5EWINNER.mp3" type="audio/mpeg"> tag inside the second audio tag.

<audio id="carteSoudCtrl">
  <source src="http://soundjax.com/reddo/17350%5EClick02.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>
<audio id="carteSoudCtrl1">
    <source src="http://soundjax.com/reddo/90754%5EWINNER.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

Jquery file :

//if you want to play first file 
$('#carteSoudCtrl')[0].play();
//if you want to play second file
$('#carteSoudCtrl1')[0].play();