Why can't JavaScript .play() audio files on iP

2019-02-11 18:55发布

问题:

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

This works great on desktop browsers (tested in Edge and Chrome), but it doesn't play on Safari on iPhone.

I've looked around Stack Overflow, and I found some answers from a couple of years ago that it's not possible to play audio from Safari unless you're in that full screen player. Is this still the case?

回答1:

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.



回答2:

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.