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();

document.body.appendChild(audio);

audio.src='/Content/Audio/timer_001.mp3';

audio.loop = true;

var initSound = function () {

audio.play();

setTimeout(function () {

audio.pause();

}, 0);

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

audio.pause();

}

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


So the main idea is to call audio.play 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 :)




1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y