Skip to content Skip to sidebar Skip to footer

Javascript Settimeout Works On Desktop, Not On Android?

I have a function that plays an different audio file at random every n seconds (based on input from a web page) when the user hits start. As you would expect, it stops when they h

Solution 1:

The issue is caused by most mobile browsers, which block videos and sounds from being played without user interaction (loading them may result in extra costs for the user, depending on their data contract).

So you can't use new Audio() after a setTimeout. What you can do, however, after at least one user interaction, is replace the src of an audio element and make it play. The good news is: you do require at least one user interaction already.

1. First step, add an <audio> element in your HTML:

<audio id="sound"></audio>

2. When the page is done loading the HTML, save that element in the audio variable, by adding this at the end of your code:

window.addEventListener('DOMContentLoaded', function(){
    audio = document.getElementById('sound');
});

3. In your playAudio function, instead of using audio = new Audio(), do this:

audio.src = fileToPlay;

Post a Comment for "Javascript Settimeout Works On Desktop, Not On Android?"