如何使用jQuery和Javascript在多次单击时播放相同的声音

How do I play the same sound on multiple clicks, using jQuery and Javascript

本文关键字:播放 声音 单击 jQuery 何使用 Javascript      更新时间:2023-09-26

目前,当我的泡泡弹出时,我会发出爆炸声,使用jQuery的爆炸效果。我希望能够点击一个又一个气泡,而不必暂停等待另一个声音结束。我尝试过使用一个变量来更改为另一个音频对象,但没有成功。任何帮助都将不胜感激!

同样的问题也发生在jsfiddle.net/xbrjp/1/中

我的HTML

<body style="background:black;">
<style>
.circleBase {
    -webkit-border-radius: 999px;
    -moz-border-radius: 999px;
    border-radius: 999px;
    behavior: url(PIE.htc);
}
.type1 {
     padding:20px;
    background: white;
    border:1px solid black;
    color:black;
}
</style>
<div class="circleBase type1" style="display:table-cell; vertical-align:middle;">
<div align="center">Bubble 1</div></div>
<div class="circleBase type1" style="display:table-cell; vertical-align:middle;">
<div align="center">Bubble 2</div></div>
<div class="circleBase type1" style="display:table-cell; vertical-align:middle;">
<div align="center">Bubble 3</div></div>
</body>
<script>
$( ".type1" ).click(function() {
  $( this ).toggle( "explode", {pieces: 50 }, 2000);
});
$(document).ready(function() {
        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src',                              'http://www.soundjay.com/mechanical/sounds/explosion-01.mp3');
        //audioElement.load()
        $.get();
        audioElement.addEventListener("load", function() {
        audioElement.play();
        }, true);
        var audioElement2 = document.createElement('audio');
        audioElement2.setAttribute('src', 'http://www.soundjay.com/mechanical/sounds/explosion-01.mp3');
        //audioElement.load()
        $.get();
        audioElement2.addEventListener("load", function() {
        audioElement2.play();
        }, true);
    var x = 0;
    if(x == 0) {
            $('.type1').click(function() {
            audioElement.play();
            });
            x = 1;
        }
        if(x == 1) {
            $('.type1').click(function() {
            audioElement2.play();
            });
            x = 0;
        }

        $('.pause').click(function() {
        audioElement.pause();
        });

});
</script>

我实际上会为每个气泡创建一个<audio>元素:

http://jsfiddle.net/8qc9V/

$(document).ready(function () {
    $(".type1").click(function () {
        $(this).toggle("explode", {
            pieces: 50
        }, 2000);
        $(this).find('audio').get(0).play();
    });
    $('.type1').each(function() {
        $('<audio/>')
        .attr('src','http://www.soundjay.com/mechanical/sounds/explosion-01.mp3')
        .appendTo(this);
    });
});