How to Add Sound/Audio Effects in HTML5 Canvas Element

HTML5 canvas is a good playground if you are kind of creative guy. If you are developing a game on the canvas you will surely like to add the sound effects in it. In HTML5 you can play the sound/audio files using the <audio> element. But you cannot use <audio> element directly while developing your own game or animation. But using JavaScript, you can do it very easily. I have used enough sound effects in my game Beerchaser. To add the sound/audio on your canvas just need to add following lines in JavaScript file:

var audio = new Audio("files/sounds/audio.mp3");;

But unfortunately the browsers do not support audio formats in similar way. First you need to identify what audio format your browser supports and then play the exact format. mp3 and wav formats are enough to cover all browsers. The following code detects the audio format supported by your browser:

var audioType;
var audio = new Audio();
if (audio.canPlayType("audio/mp3")) {
audioType = ".mp3";
} else {
audioType = ".wav";

//Function to play the exact file format
function playAudio(){
var audio = new Audio("files/sounds/audio" + audioType);;

Now you can accordingly play the exact audio file. Remember that its always a good idea to keep your audio files in both formats for the cross browser compatibility.

Written by Arvind Bhardwaj

Arvind is a Magento and WordPress expert with more than 6 years of industry wide experience.