I\'ve got a JavaScript web app working that plays some audio periodically like this:
var SOUND_SUCCESS = new Audio(\'success.mp3\');
SOUND_SUCCESS.play();
iOS disables autoplay, instead requiring that play be initiated as part of a user interaction (e.g., you can start playback within a touchstart listener). There's a bit of documentation about this on Apple's developer documentation. There's also this article Overcoming iOS HTML5 audio limitations on IBM's developer site that has examples and more detail.
To add to xingliang cai's response, here's a code sample I got to work for me:
const soundEffect = new Audio();
// onClick of first interaction on page before I need the sounds
soundEffect.play();
// later on when you actually want to play a sound at any point without user interaction
soundEffect.src = 'path/to/file.mp3';
soundEffect.play();
IOS on mobile disable automatic sound playing by default. So to get around this problem. You could put enable/disable switch button somewhere on the page and play some sound using an audio element("audioElement") if the user click the button switch.
After that, the same "audioElement" can be used to play future sounds by changing its "src" attribute and call its "play()" method, without any further user interaction.
Haha, i outsmarted it like this.
Put in the page the audio tag with autoplay (true)
<audio id="beep" src={Assets.SOUND_BEEP} autoPlay />
It will play the sound once the element is mounted. (Even on safari iOS).
Then it seems you can play it whenever you want again by calling
document.getElementById('beep').play();
But now you may say, but I don't want to play the sound as autoplay.
Yes, I outsmarted it to put the "muted" property on that, and then set it to false when playing.
<audio id="beep" src={Assets.SOUND_BEEP} autoPlay muted />
And play:
document.getElementById('beep').muted = false;
document.getElementById('beep').play();