+ 5
[SOLVED] How to play audio in Javascript without any action by user.
When I try to run this code, I get an exception that goes "play() can only be initiated by a user gesture" Any way to fix this? https://code.sololearn.com/WiYM4qJMvMK8/?ref=app
14 ответов
+ 8
I got it to work with howler js,
https://code.sololearn.com/WsuKTARh0Y2x/?ref=app
and the Web Audio API
https://code.sololearn.com/W8ODQlIstFcN/?ref=app
Works like a charm 😊
+ 7
That's the point. Some browsers enforce such restrictions to prevent malicious scripts (commonly found in spam and scam sites) from autoplaying stuff without the user asking it to.
You can either disable your browser's autoplay policy, or request user permission to execute media.
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play#Usage_notes
https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
+ 4
Coder I wanted to play a sound without any intervention from the user. It appears that that is not allowed, at least not on Android.
+ 4
Even I have a lot of struggle finding for a pure JavaScript solutions 😂😂
But I got only this thing working
On pc you can just play whatever
Because of device security rules its prohibited
+ 4
「HAPPY TO HELP」 what if I don't exactly want it to play when the page loads, but at any other given time, again, without a user gesture?
+ 3
thanks Coder to ping me 😄
There is nothing you can do on this
But I have a hack..
Just ask the user "play sound"
With yes no button
And made useres to click on a "yes" button
Then on click of the button play all the sounds you have in zero volume and in loop mode *important*
Then whenever you want the sound to play
Set audio.currentTime = 0;
And audio.volume = 1;
There you go you can play the sound as you wish
Look at this code I made I used the same technique. When user presses the start button I play the sound and set the time and volume when I really need to play the sound
https://code.sololearn.com/Wq2g285mw9FA/?ref=app
+ 2
Coder that's what!!
Like in old games just make a demo prompt to ask user play sound or not
On click yes of the prompt
Play all the sounds you want to play
In zero volume and loop = true..
And when you need your sound to play
Just set the currentTime to 0 and volume 1
+ 2
Coder and that's the only way
Because playing audio must have to be performed only on user action
So you must have to bind some user action event to play the audio..
+ 2
Add audio url to src when you want it play, else remove it?