Javascript音频播放两次

Javascript音频播放两次

问题描述:

我正在构建一个简单的HTML5/Javascript游戏,希望在单击某些内容时播放声音文件.

I'm building a simple HTML5/Javascript game and wish to play a sound file when something is clicked.

我有以下内容:

function tileClickListener(e) {
    e.preventDefault();
    console.log('tile clicked');

    var audio = new Audio('sounds/click.wav');
    audio.play();
}

但是,它总是在单击时播放两次.点击事件仅触发一次(已使用断点和日志进行测试).

However it always plays twice on click. The click event only fires once (tested with a breakpoint and a log).

游戏是普通JS,没有jQuery.

The game is vanilla JS, no jQuery.

我缺少明显的东西吗?

我发现了其他与视频有关的问题,但对音频没有可靠的解决方案.

I've found other questions relating to video but no solid solution to audio.

这个天真的实现对我来说只播放一次.

This naive implementation seems to play only once for me.

Array.from(document.querySelectorAll(".tile")).forEach(function(el){
  el.addEventListener("click", tileClickListener);
});

function tileClickListener(e) {
    e.preventDefault();
    console.log('tile clicked');
    var audio = new Audio('http://www.soundjay.com/button/beep-01a.wav');
    audio.play();
}

.tile{
  height: 100px;
  width: 100px;
  background-color: aliceblue;
  border: solid 1px;
  text-align: center;
  line-height: 100px;
}

<div class="tile">click</div>