0

Struggled with this for hours - Can't seem to get the audio file to play once I click an HTML element.

var bb = document.querySelector(".soundfile");

function playAudio() {
  bb.play();
}


document.querySelector(".btn-hold").addEventListener("click", playAudio);
<audio class="soundfile">
  <sound src="sound.mp3" type="audio/mpeg">
</audio>

<button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>

this is different to other questions

Phil
  • 141,914
  • 21
  • 225
  • 223
James Henders
  • 161
  • 1
  • 1
  • 5
  • Possible duplicate of [Javascript Audio Play on click](https://stackoverflow.com/questions/18826147/javascript-audio-play-on-click) – Pararera Nov 22 '18 at 01:18
  • I'm a little confused by your code. If you're asking about playing a sound file from a click, why are you showing buttons labeled "new game", "roll dice" and "hold"? Can you create a plain [mcve] instead? – Mike 'Pomax' Kamermans Nov 22 '18 at 01:39
  • 3
    it should be `` not ``. No? – yqlim Nov 22 '18 at 01:39
  • @Mike'Pomax'Kamermans I imagine OP wants to play a sound when you click the "Hold" button. There's enough information here to understand the problem (which YongQuan has solved above) – Phil Nov 22 '18 at 01:40
  • As do I, and the [mcve] request is not just for us, but also for James himself: 99.9% of the time simply the exercise of creating that minimal example makes you discover the _actual_ problem all on your own, even if you already had your SO question written up. – Mike 'Pomax' Kamermans Nov 22 '18 at 01:41

2 Answers2

3

It should be <source>, not <sound>.

<audio class="soundfile">
  <source src="sound.mp3" type="audio/mpeg">
</audio>

It should be working after you change to the correct element.

If it's still not working, then there might be a problem in some other part of your code and we have not enough information to help you diagnose that.

yqlim
  • 6,303
  • 3
  • 19
  • 39
0

Replace <sound> tag with <source>

Ryuujo
  • 583
  • 1
  • 8
  • 25