James J James J - 3 months ago 27
Javascript Question

Javascript Audio plays twice

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

I have the following:

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

The game is vanilla JS, no jQuery.

Am I missing something obvious?

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

Answer

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>