简体   繁体   中英

Play audio audio file at a time

I have 5 images, each has an audio file that plays when the image is clicked.

I want the audio that is playing for one image to stop when another image is clicked and then play the audio for that image.

$('.cl').click(function() {
  var DOMElem = $('.cs').get(0);
  DOMElem.paused ? DOMElem.play() : DOMElem.pause();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img class="cl" src="photo/198.jpg" />
</br>
<audio class="cs">
  <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<img class="cl" src="photo/198.jpg" />
</br>
<audio class="cs">
  <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<img class="cl" src="photo/198.jpg" />
</br>
<audio class="cs">
  <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>

You are getting first audio object every time. You need to get the object with respect to img

$('.cl').click(function () {
   var DOMElem = $(this).next().next().get(0);
   DOMElem.paused ? DOMElem.play() : DOMElem.pause();
});

A better approach is to make a container div for each image and audio and when you click the image you can get the audio object with respect to container.

<div class="audioContainer">
        <img class="cl" src="photo/198.jpg" />
        </br>
        <audio class="cs">
            <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
        </audio>
    </div>
    <div class="audioContainer">
        <img class="cl" src="photo/198.jpg" />
        </br>
        <audio class="cs">
            <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
        </audio>
    </div>
    <div class="audioContainer">
        <img class="cl" src="photo/198.jpg" />
        </br>
        <audio class="cs">
            <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
        </audio>
    </div>
    <script>

         var DOMElem;
    $('.cl').click(function () {
        if (DOMElem) {
            if (!DOMElem.paused)
                DOMElem.pause();
        }
        DOMElem = $(this).parent().find('.cs').get(0);
        DOMElem.play();
        console.log(DOMElem);
    });
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM