Why can't JavaScript .play() audio files on iPhone safari?

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.