24

Using HTML 5, I want to play multiple sounds simultaneously. how can I do it?

Here's what I currently have:

<audio controls="controls">
    <source src="audio/(TESBIHAT).mp3" type="audio/mpeg" />
    <source src="audio/Dombra.mp3" type="audio/mpeg" />

    <embed height="50px" width="100px" src="audio/(TESBIHAT).mp3" />
    <embed height="50px" width="100px" src="audio/Dombra.mp3" />
</audio>
pitamer
  • 905
  • 3
  • 15
  • 27
Polymorphism
  • 375
  • 1
  • 3
  • 11

1 Answers1

28

With JavaScript and the HTML5 Audio API you could do something like this:

var snd1  = new Audio();
var src1  = document.createElement("source");
src1.type = "audio/mpeg";
src1.src  = "audio/Dombra.mp3";
snd1.appendChild(src1);

var snd2  = new Audio();
var src2  = document.createElement("source");
src2.type = "audio/mpeg";
src2.src  = "audio/(TESBIHAT).mp3";
snd2.appendChild(src2);

snd1.play(); snd2.play(); // Now both will play at the same time

I have tested this in Chrome v. 20, and it seems to work :)

The <source> tag is used to specify different formats of the same file - such that the browser can choose another format as fallback in case the first one is not supported. That is why your own suggested solution does not work.

Lasse Christiansen
  • 10,205
  • 7
  • 50
  • 79
  • Thanks for reply Chrome and IE work but only n't working Opera not important thanks :) – Polymorphism Jul 26 '12 at 11:42
  • 1
    It won't work in Opera because it doesn't support mp3. Use .ogg instead http://html5doctor.com/html5-audio-the-state-of-play/ – trainoasis May 19 '14 at 14:49
  • Will this work on mobile devices that only support one audio stream at a time? – Kokodoko Nov 05 '15 at 13:10
  • 2
    Can you do it without creating elements? – Pixsa Nov 08 '18 at 15:46
  • I tried it but it doesn't work. Shows `Uncaught (in promise) DOMException` – Arvind K. Jan 28 '19 at 13:49
  • @ArvindK. the browser will show that when it prevents a sound from auto-playing, there might not be any problem with your code. See [this information](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API#Controlling_sound) from the MDN which is relevant (even though it's talking about the Web Audio API). **TL;DR:** Click on your page before the sound tries to play and you probably won't get that error. – Eric Lindsey May 19 '19 at 05:49
  • Doesn't work well on mobile devices – MAZ Dec 25 '21 at 11:03