1

How do I play a sound / notification on a page, even though that page is not active in focus?

function checkOrder()
{
    ...
    ...
    ...

    if (isOrder) {
        var audio = new Audio('/path/to/audio/file.mp3');
        audio.play();
    }
}

Usually the sound only plays when I'm active on the page. I need the sound to reproduce even if I'm active in another window.

  • Maybe the answers to [this question](https://stackoverflow.com/questions/21463752/javascript-audio-object-vs-html5-audio-tag) will be of interest :o) – agrm Oct 24 '17 at 14:46

1 Answers1

1

There are a couple ways to do this:

1) HTML allows you to use the html <audio> tag in most modern browsers for this very purpose

2) Use jQuery to create a new Audio object (as you have already done) and pass in the url to the sound file as a parameter.

WARNING - example is quite loud by default

var audio = new Audio("https://www.computerhope.com/jargon/m/example.mp3");

$('#start').click(function() {
  audio.play()
});

$('#pause').click(function() {
  audio.pause()
});
.container
{
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <label>Using audio tag </label><br/>
  <!-- use audio tag !-->
  <audio id="playAudio" controls>
  <source src="https://www.computerhope.com/jargon/m/example.mp3" />
  </audio>
</div>

<div class="container">
  <label>Using jQuery </label><br/>
  <!-- add a button and handle this in jQuery !-->
  <div>
    <button id="start">play</button>
    <button id="pause">pause</button>
  </div>
</div>

Here is the full list of supported browsers for the <audio> tag:

Support browsers

Audio credit to computerhope.com

Master Yoda
  • 4,334
  • 10
  • 43
  • 77