Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 544
Leon Overweel Avatar asked Aug 02 '15 21:08

Leon Overweel


People also ask

Why is my JavaScript not working on my iPhone?

On an iPhone, JavaScript should be turned on by default, but if it was disabled at some point, many websites will appear broken in the Safari browser. To enable JavaScript, go into the Settings app on your iPhone, click "Safari," then "Advanced," and swipe the JavaScript button to the right so it appears green.

Why is JavaScript not working in Safari?

To enable the JavaScript in Safari Browser, you need to open the Settings on your iOS device and then go to the advanced option. Under the advance option, toggle the button of the JavaScript and turn it ON.


2 Answers

To add to xingliang cai's response, here's a code sample I got to work for me (edited below to work on iOS14, thanks @AndrewL!):

const soundEffect = new Audio(); soundEffect.autoplay = true;  // onClick of first interaction on page before I need the sounds // (This is a tiny MP3 file that is silent and extremely short - retrieved from https://bigsoundbank.com and then modified) soundEffect.src = "data:audio/mpeg;base64,SUQzBAAAAAABEVRYWFgAAAAtAAADY29tbWVudABCaWdTb3VuZEJhbmsuY29tIC8gTGFTb25vdGhlcXVlLm9yZwBURU5DAAAAHQAAA1N3aXRjaCBQbHVzIMKpIE5DSCBTb2Z0d2FyZQBUSVQyAAAABgAAAzIyMzUAVFNTRQAAAA8AAANMYXZmNTcuODMuMTAwAAAAAAAAAAAAAAD/80DEAAAAA0gAAAAATEFNRTMuMTAwVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/zQsRbAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/zQMSkAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV";  // later on when you actually want to play a sound at any point without user interaction soundEffect.src = 'path/to/file.mp3'; 
like image 124
user2415116 Avatar answered Sep 18 '22 19:09

user2415116


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.

like image 20
Ed Ballot Avatar answered Sep 18 '22 19:09

Ed Ballot