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?
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.
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.
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';
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With