Ionut Necula
Ionut Necula

Reputation: 11472

How to play audio using setTimeout on mobile devices?

I'm trying to play an HTML5 audio element on mobile devices(tested on Samsung Galaxy Tab 4 and mobile phone) using jQuery's function setTimeout(), but nothing is happening. If I remove the audio.play() from the setTimeout function the sound plays ok.

I have to say that on desktop and laptop works fine.

Why this does not work on mobile devices:

var audio = document.getElementById('audio_1');
setTimeout(function() {
  audio.play();
}, 3000);

Upvotes: 0

Views: 3399

Answers (1)

Ionut Necula
Ionut Necula

Reputation: 11472

I will answer my question at the bottom. In comments A. Wolff and LGSong said that is not possible what I'm trying to achieve, but I thinked of a dirty trick that solved my problem. I started and then immediatelly paused the audio before the setTimeout function and then everything worked fine. So this is it, hoping will help someone in the future too:

var audio = document.getElementById('audio_1');
audio.play();
audio.pause();
setTimeout(function() {
  audio.play();
}, 3000);

Upvotes: 5

Related Questions