How to auto-play audio in Safari with JavaScript
Playing audio files in JavaScript is easy until it doesn’t work. Safari will refuse to play any audio until the user has tapped something that triggers audio.
Mobile Safari doesn’t even starting loading any of the audio files until you want to play one from a user tap. This causes a lag on the first time the user decides to play a sound. It only loads the metadata (readyState is stuck at 1).
The solution: Play every single audio file at the same time on the first user tap! This will cause an explosion of sound into the user’s unsuspecting earholes. Actually, you can just stop each audio immediately when you first play it. The user won’t hear anything.
<script>
var scan=new Audio("YOUR_FILE_PATH_HERE/beep.mp3");
var thank=new Audio("YOUR_FILE_PATH_HERE/thankyou.mp3");
var allowPlay=0;
var otherAud=[];
otherAud.push(scan);
otherAud.push(thank);
document.body.addEventListener('touchstart', tapped, false);
document.body.addEventListener('click', tapped, false);
var tapped = function() {
if(otherAud) {
for(var audio of otherAud) {
audio.play()
audio.pause()
audio.currentTime = 0
}
otherAud = null;
allowPlay=1;
}
};
var stop = function() {
allowPlay=0;
scan.pause();
thank.pause();
document.body.removeEventListener('touchstart', tapped, false);
document.body.removeEventListener('click', tapped, false);
}
var playAudScan = function(){
if(allowPlay)
{
scan.play();
}
};
var playAudThank = function(){
if(allowPlay)
{
thank.play();
}
};
</script>
We hope this one helps you,
------------------
Solution found by: Kartik, Vijay, Shivangi, Shivani.