Audio on the same page. Play at each other

Asked

Viewed 44 times

-2

I’m trying the following:

I created audio1 and audio2 based on what I learned here on the forum. It turns out that the result was not what was desired, IE, clicking the two sounds is heard. I would like to click on one (play) or the other of that pause. I would not like to allow listening sounds at the same time. Here is an example: insert link description here

$(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>

Someone can ,and help. Thank you

  • Daniel, that’s exactly it. Success for you. Thank you so much.

1 answer

1

Carlos, use the event play in place of the event click:

$(function(){

  $("#audio1").on('play', function(){
    var pe = $("#audio2").get(0);

    if(pe.paused == false)
      pe.pause();
  });

  $("#audio2").on('play', 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.