Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have sound play when alert is triggered

Tags:

javascript

So I have in my javascript an if statement. When it returns true it opens an alert box and plays an alarm sound. The problem is that the sound doesn't play until I hit 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 which is around 6 seconds long to play until it is at the end or until the user hits closes out of the dialog. But really getting the alarm to sound before closing the alert box would be good enough.

like image 820
moosilauke18 Avatar asked Feb 16 '14 18:02

moosilauke18


2 Answers

Preload your audio file in the html beforehand like :

<audio id="xyz" src="whatever_you_want.mp3" preload="auto"></audio>

if(x > 10)
{
    document.getElementById('xyz').play();
    alert("Thank you!");
}

This should surely work.

like image 67
MixCoded Avatar answered Sep 28 '22 07:09

MixCoded


For a quick and dirty beep, you could use this "beep" MP3. It's awful.

Here's a working example:

var mp3_url = 'https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3';

(new Audio(mp3_url)).play()

If you want to make it extra extra annoying (I needed a psuedo-pager to alert myself when an appointment slot opened up), just repeat the beep every second:

for (i=0; i<10; i++) {
  setTimeout(function(){(new Audio(mp3)).play()}, i * 1000)
}

It's truly horrendous, worse that marquee text! You are a bad person if you put that "repeated beep" code snippet in a real web page. Worked great as a hacky pager though.

like image 40
Dave Dopson Avatar answered Sep 28 '22 08:09

Dave Dopson