HTML5 audio - play sound repeatedly on click, regardless if previous iteration has finished

风格不统一 提交于 2019-12-03 02:57:31
Maverick

Once the gun_bang.wav is preloaded, you can dynamically make new elements with that sound attached to it, play the audio, and then remove them when the audio has finished.

    function gun_bang(){
        var audio = document.createElement("audio");
        audio.src = "http://www.seancannon.com/_test/audio/gun_bang.wav";
        audio.addEventListener("ended", function () {
            document.removeChild(this);
        }, false);
        audio.play();   
    }

    $('#' + CANVAS_ID).bind(_click, function() {
        gun_bang();
        adj_game_data(GAME_DATA_AMMO_ID, -1);
        check_ammo();
    }); 

I know it's a very late answer, I just wanted to , but seeking for a solution I found that in my case the best one was to preload the sound and then clone the node each time I want to play it, this allows me to play it even if the previous has not ended:

var sound = new Audio("click.mp3");
sound.preload = 'auto';
sound.load();

function playSound(volume) {
  var click=sound.cloneNode();
  click.volume=volume;
  click.play();
}

You can wrap the following with your own program-specific click logic, but the following demonstrates 3 gun sounds at the same time. If you want any kind of delay, you can introduce a minor sleep() function (many kludge hacks for this are easily found), or you can use setTimeout() to call subsequent ones.

<audio id="gun_sound" preload="preload">
    <source src="http://www.seancannon.com/_test/audio/gun_bang.wav" />
</audio>

<script type="text/javascript">
jQuery(document).ready(function($){

  $('#gun_sound').clone()[0].play();
  $('#gun_sound').clone()[0].play();
  $('#gun_sound').clone()[0].play();

});
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!