Javascript Audio Play on click

dA_uNknOwN picture dA_uNknOwN · Sep 16, 2013 · Viewed 183.6k times · Source

I have a javascript code to start a sound on click . It works on chrome but on firefox it starts onload, but I want it onclick there too.

Can anyone help?

<script>
var audio = new Audio("http://music.ogg" ) ;

audio.oncanplaythrough = function(){
audio.play();
}

audio.loop = true;

audio.onended = function(){
audio.play();
}

</script>

<input type="image" src="http://button.png" onclick="audio.play()">

Answer

Arunkumar picture Arunkumar · Sep 16, 2013

Try the below code snippet

<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onclick="play()">
    <audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>

  </body>
</html>