Play sound when an alert is triggered

So, I have an if statement in my javascript. When it returns true, it opens a warning window and plays a sound. The problem is that the sound does not play until I press the ok button.

Here is the relevant information:

if (x > 10) { var snd = new Audio('/alarm.mp3'); snd.play(); alert("Thank you!"); } 

Ideally, I want the sound to last about 6 seconds, until it is at the end or until the user hits, closes from the dialog box. But actually receiving a sound signal before closing the notification window would be good enough.

+6
source share
4 answers

Preload the audio file in html, for example:

 <audio id="xyz" src="whatever_you_want.mp3" preload="auto"></audio> if(x > 10) { document.getElementById('xyz').play(); alert("Thank you!"); } 

That should work.

+14
source

Why not use HTML5 audio events.

The event ended with a trigger after the sound has finished playing.

 snd.addEventListener('ended', showAlert); function showAlert() { alert("YOUR MESSAGE"); } 
+1
source

You can try setTimeout () .

 if (x > 10) { var snd = new Audio('/alarm.mp3'); snd.play(); setTimeout(function(){alert("Thank you!")},6000); } 
0
source

You can use:

 var snd = new Audio('/alarm.mp3'); snd .onended = function () { alert("Thank you!"); }; snd .play(); 
0
source

All Articles