简体   繁体   English

一次播放音频音频文件

[英]Play audio audio file at a time

I have 5 images, each has an audio file that plays when the image is clicked.我有 5 张图片,每张图片都有一个音频文件,可以在点击图片时播放。

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.您每次都会获得第一个audio对象。 You need to get the object with respect to img您需要获取关于imgobject

$('.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,当您单击image您可以获得与容器相关的音频对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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