Play one audio at a time

Asked

Viewed 1,606 times

0

I have that 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 both of them play at the same time. How to set to play one at a time.

  • 1

    Did not load any image, could put HTML?

  • 1

    I tested here and worked each independent, changes the audio SRC DO to SRC="http://www.w3schools.com/html/horse.mp3"

  • There are two audios on the same page. If you play them both, they will play simultaneously and I didn’t want that to occur.

  • @Allanconservajr. and what do you want to happen if the person gives play in both?

2 answers

3

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

Follow a very 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>
<audio id="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>

1

I don’t know if I understand you right, 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>
	<audio id="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.