How to play audio in html5 canvas using audio tag

how to play sound in html5 canvas using javascript - nibunan

how to play wav file in html5 canvas using javascript - nibunan

how to write program to play wav file in html5 canvas using javascript- nibunan

how to write program to play sound in html5 canvas using javascript- nibunan

how to write code to play audio in html5 canvas using javascript- nibunan

Playing sound is the most important thing while developing the game using html5 canvas. This article explains how to create the canvas that plays sound in background using simple audio tag in HTML5.

Demo

Open with new tab

Source


      <html>
      <head>
      <title>Audio Example - Nibunan</title>
      <script type="text/javascript">
      function playAudio() {
      var audio = document.getElementById("myAudio");
      audio.play();
      }

      function pauseAudio() {
      var audio = document.getElementById("myAudio");
      audio.pause();
      }
      </script>
      </head>
      <body>
      <canvas id="myCanvas" width="700" height="100"
      style="background-color:green">
      </canvas>
      <script type="text/javascript">
      var canvas= document.getElementById("myCanvas");
      var context2d=canvas.getContext("2d");
      context2d.fillStyle ='violet';
      context2d.font = "30px Verdana";
      context2d.fillText("This is the canvas with background music" , 40,60);
      </script>
      <br />
      <button onclick="playAudio()">Play</button>
      <button onclick="pauseAudio()">Pause</button>
      <audio style="display:none" id="myAudio" controls="" loop="">
      <source src="mason2.wav">
      </audio>
      </body>
      </html>