Code Optimization

Interesting things about software development and code optimization

Play audio with javascript under mobile browsers

Hello friends,

as some of you may know - there is a problem to start playing audio using javascript under mobile browsers.

This is a security feature and to be able to start playing audio you have to provide user with a button that user has to click to start playing audio.

In my case I was trying to play short audio file after some period of time but with no luck :(

After some research I found information that it was a security issue (not issue but security reason), and what I had come to is the following:

var audio = new Audio();



audio.loop = true;

var initSound = function () {;

setTimeout(function () {


}, 0);

document.removeEventListener('touchstart', initSound, false);



document.addEventListener('touchstart', initSound, false);

So the main idea is to call and pause methods on first touch event.

After that each time your javascript code calls play or pause methods - browser plays audio.

Thank you,

see you :)