+ 1

How to play sound in my timer?

I am trying to make a code of a timer which plays a sound when the time entered is over but it does not play and shows an error. Please tell me how to fix this error and play the sound after the time is over. This is my code | | \/ https://code.sololearn.com/Wj0etkhlq2LI/?ref=app

29th Mar 2020, 1:43 PM
Vasu Vijay
Vasu Vijay - avatar
7 Respuestas
+ 1
Can you try this. Let me know if it works or not. https://code.sololearn.com/W6z6g5HUfaU0/?ref=app
29th Mar 2020, 2:47 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
Vasu Vijay , can you please recheck? This is working for me. *Alarm sound😬*
29th Mar 2020, 2:24 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
That too working for me Vasu Vijay
29th Mar 2020, 2:30 PM
Monkey D. Luffy
Monkey D. Luffy - avatar
+ 1
Vasu Vijay , I'm glad it works 😊. However it'll not be fine if you just use that code without understanding why it works and what changes I have made. So here is explaination. 1. I have made `sound` variable global because I need to use it in more than one function. I assigned audio element to sound variable within window.onload =()=>{} anonymous function , it's called when DOM is ready. 2. As play method requires user interaction I have used a workaround. I'm calling sound.play() in start method which is called on user interaction (click). But we don't want to play audio when timer starts so I called sound.pause() immediately after sound.play(). 3. Lastly audio is played in playSound() method. (user interaction is not required this time).
29th Mar 2020, 3:53 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
🇮🇳Omkar🕉, Thank you so much for making me understand. At first when I saw your code honestly I was trying to understand how your changes removed the error and made the sound play when the time is over but I can't understand. However, now I understand. Once again thank you.
29th Mar 2020, 3:58 PM
Vasu Vijay
Vasu Vijay - avatar
0
But in my phone it is not working and showing this error: Uncaught (in promise) NotAllowedError: play () can only be initiated by a user gesture. Line: 8
29th Mar 2020, 2:28 PM
Vasu Vijay
Vasu Vijay - avatar
0
This code works 🇮🇳Omkar🕉
29th Mar 2020, 3:30 PM
Vasu Vijay
Vasu Vijay - avatar