Play one audio at a time

0

I have this scenario:

<audio id="audio1" controls>
    <source src="http://stream?type=.mp3"type="audio/mp3" />
</audio><br />

<audio id="audio2" controls>
    <source src="http://stream?type=.mp3"type="audio/mp3" />
</audio><br />

If you play you both play at the same time. How to set to play one at a time.

    
asked by anonymous 11.11.2015 / 15:47

2 answers

2

I think it would be better to keep a player and use a javascript function to change the src and run, so you can have as many sounds as you want without having to worry about getting controlled by running multiple players.

Here's a simple example.

var tocar = function(url){
  $("#audioPlayer").attr('src',url);   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><audioid="audioPlayer" controls autoplay></audio>
<br>
<button onclick="tocar('http://www.w3schools.com/tags/horse.mp3');">Horse.mp3</button>
<button onclick="tocar('http://www.w3schools.com/tags/horse.ogg');">Horse.ogg</button>
<button onclick="tocar('https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg');">Exemple.ogg</button>
<button onclick="tocar('https://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg');">ACDC.ogg</button>
    
13.09.2016 / 19:01
1

I do not know if I understand correctly, but you can perform this control via Jquery.

$(function(){
  $("#audio1").on('click', function(){
    var pe = $("#audio2").get(0); 
    if(pe.paused == false)
      pe.pause();
  });
  $("#audio2").on('click', function(){
    var pe = $("#audio1").get(0); 
    if(pe.paused == false)
      pe.pause();
  });
});
<html>
	<head>
		<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script></head><body><audioid="audio1" controls>
	    <source src="http://w3schools.com/html/horse.mp3"type="audio/mp3" />
	</audio><br />

	<audio id="audio2" controls>
	    <source src="http://w3schools.com/html/horse.mp3"type="audio/mp3" />
	</audio><br />
</body>
</html>
    
11.11.2015 / 20:29