I have been searching all day. I know that autoplay does not work on mobile and that makes sense. But i want to know why is this not working. Is there a work around for this. The below code works perfectly on desktop but not on mobile.
var audio = new Audio('sound.mp3');
audio.play();
I have been searching all day. I know that autoplay does not work on mobile and that makes sense. But i want to know why is this not working. Is there a work around for this. The below code works perfectly on desktop but not on mobile.
var audio = new Audio('sound.mp3');
audio.play();
Share
Improve this question
edited Sep 21, 2017 at 14:20
rak007
1,01114 silver badges27 bronze badges
asked Sep 21, 2017 at 13:55
user7498826user7498826
1733 silver badges11 bronze badges
3
- 1 This might help, seems very similar to your problem: pupunzi.open-lab./2013/03/13/… – Robbie Milejczak Commented Sep 21, 2017 at 13:58
- stackoverflow./questions/42160528/… it just doesn't on some, read that link – mlegg Commented Sep 21, 2017 at 15:05
- @RobbieMilejczak This helped thanks – user7498826 Commented Sep 22, 2017 at 6:53
2 Answers
Reset to default 3Very old question but I ran into it a few times on my journey to the solution to my problem which was that audio seemed to work perfectly fine on desktop but not at all on select mobile browsers.
My problem was that in a touchevent
I was doing e.preventDefault()
which (somehow?) made the event 'not trusted' meaning everything looked fine but no audio would play.
I fixed it by just not using the touch event and relying on the click event which is fired after and setting touch-action: manipulation
in the css. Not the best solution, but hey. Pretty silly the event bees non-trusted on a tap on a control to play the sound with a prevent default so that it won't zoom in on a double tap.
Hopefully this helps someone with a similar problem.
(from ment from Manuel Graf on this question)
As others have alluded, a mon problem with JS html5 audio on mobile is the scope that instantiates the Audio object needs to be in response to a user action.
Maybe this is in a onReady function handler, you can handle some kind of click or touch action that initializes the Audio object.
var audio;
$("#startAudio").on("click", function(e){
if(!audio){
audio = new Audio('sound.mp3');;
}
});
This will download the audio file, but should not play it automatically.
Once initialized, your code can play the audio audio.play();
as needed