-1

I'm not sure how to format a function that I can call with Onclick in the HTML.

I've tried using several methods posted here on StackOverflow and W3 Schools. The sounds are stored locally in the main file, however, I've been trying to use a web file as well. (http://www.intriguing.com/mp/_sounds/hg/dead.wav).

<div id="play">
    <button type= button onclick = "play" >Fire!</button>
</div>  
<audio >
    <source src="Photon.mp3" type="audio/mpeg">
    <source src="Photon.mp3" type="audio/ogg">
</audio>

//Optional sound source 

function play(){
    var audio = document.getElementById("audio");
    audio.play();
}   

I want the user to hear some type of sound when they click on the Fire button. Thank You

fiza khan
  • 1,280
  • 13
  • 24
haberjin
  • 55
  • 6
  • Possible duplicate of https://stackoverflow.com/questions/18826147/javascript-audio-play-on-click – Peyman.H Feb 16 '19 at 05:50
  • A function is called by putting `()` after a reference to it. `onclick = "play()"`. Learn more about functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions – Felix Kling Feb 16 '19 at 05:50

2 Answers2

2

You are using getElementbyId("audio") but you see there is no tag with that id in the dom. So either make id of audio tag as "audio" or use

var elem = document.querySelector("audio");
himank
  • 439
  • 3
  • 5
1

Problem was in the function call

function play() {
  var audio = document.getElementById("audio");
  audio.play();
  console.log('playing')
}
<div id="play">
  <button type=button onclick="play()">Fire!</button></div>

<audio id="audio">
      <source src="Photon.mp3" type="audio/mpeg">
      <source src="Photon.mp3" type="audio/ogg">
 </audio>
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • Thanks a lot. This is the first time I've tried using audio which is no excuse for missing embarrassing details. I appreciate your help. – haberjin Feb 16 '19 at 05:59