How to get audio to play on iOS and mobile

Getting audio to play on iOS can be tricky. While you can use audio in your computer’s browser on page load without issue, iOS will not load or play audio without the user first tapping the screen. This is apparently to cut down on downloading large files without the user’s permission.

There is no way to get around this. You will ALWAYS need the user to at least tap once. But if your app requires any kind of interaction at all, this shouldn’t be a problem. If not, then maybe you can use a splash screen of some sort where the user taps “start”.

Unfortunately, it’s not always quite this straightforward, I’ve discovered. Here’s a couple of things I learned while trying to get sound to work in iOS on my Pomodoro time app.

  1. Audio will only be loaded if the user interacts with one of the following event listeners: click, touchstart, mouseup and mousedown.

  2. You have to play the audio IN the function that is called by the event listener first. Say your event listener points to myFunction1 and myFunction1 points to myFunction2, If you put audio.play() in myFunction2, it will not play. You have to play it in myFunction1. After that, you can play it from any function and it’ll still work.

  3. What if you don’t want it to play in myFunction1 though? You can suppress it my adding audio.pause() immediately after it and it will stop it from playing the first time.

Here’s how I did it:

  function myFunc2() {
    audio.play();                <--- this is the audio I really wanted to play
  }

  function myFunc1() {
    audio.play();                <--- I didn't want it to play here, but it needs to be in the function that is referenced
    audio.pause();             <--- by the event listener so it HAS to be included. So, I paused the sound right away.
  }

  document.getElementById("start").addEventListener("click", myFunc1, false);

It took me a lot of searching around to figure out how to do this so I’m putting it here to help other campers save time.Ii hope it helps!

2 Likes