Getting this ERROR when trying to play a music
I am getting this error in the console everytime I try to play a song when my timer is up. How can I do to solve it?
DOMException { code: 0, name: "NotAllowedError", message: "play() can only be initiated by a user gesture.", INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, β¦ }
13 Replies
what's this time variable?? is it how much time left of the music??
You'll want to check out the HTMLAudioElement documentation on MDN, especially the Usage Notes section https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play#usage_notes
There's an entire guide on playing audio outside of direct user interaction https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
I haven't really done much with audio in browsers, but from a quick skim, calling .play() without "direct user interaction" is considered autoplaying. My guess would be that it'll only work in an
click
eventhandler, not in code called later, though I'm not 100% sure
what I'd try myself is seeing if the audio will play when you call audio.play() inside the handler for the button click. If it does, then my next step would be to play and immediately pause the audio, then see if I can resume playing later when the timer runs out.
there's also some section about autoplaying permissions in the second link, you might be able to use that to make .play work, you'll have to read through it yourself though
let us know if you figure it outYou beat me to itπ. You could start and the immediately pause the audio when the timer starts and then play (without redefining the audio) when the timer runs out.
yeah, the not-redefining bit is probably very important
I have thrown together a quick pen to demonstrate that this works. https://codepen.io/cbolson/pen/QWZvYrZ?editors=1111
Click the βstartβ button to start the timer. (The pause button is irrelevant)
I saw if the audio would play when I call audio.play() inside the handler for the button click. But simply not work. I dunno if is because I am trying to do this through my phone or what...
check out Chris's codepen
Iβm quite happy with that. I have never used audio before π
Yours work perfectly π
I will try to do the same using your code as reference
@Chris when I clicked in the start button, the music has played, but when I put the if statement the sound stopped to been played π
π’ (it still the same code from the previously question)
You need to play() and immediately pause() the audio when you start the timer. Then, when the timer reaches 0, just play the previously paused audio.
It worked. Thanks
Just one more question, I promise. Where did u hosted the audio file on a server so that can be accessed via a URL?
The audio file that I used in the demo was just a random file that I found for the test.
If you are going to publish the project presumably you will also be able to upload your audio file too.