javascripthtml5-audio

How to play a sound on a certain condition?


I am making a web server to output the pressure values of a graph on a website. If the pressure is too low/high, I want to play a sound warning the user. I cannot seem to find the way to do this, as I have a unique problem: I have to have <meta http-equiv="refresh" content="1" /> in my html code. This of course refreshes the page every second, so even if I have a button for the user to click the first time the pressure is too low, the page is instantly reloaded and I get a "Uncaught (in promise) DOMException" in the console next time the audio is supposed to play. Here is the code I have so far, shortened to show the necessary parts:

HTML:

<audio id="alert_sound" controls>
  <source src="chime.mp3" type="audio/mp3">
  <source src="chime.ogg" type="audio/ogg">
</audio>

Javascript:

var arduino = [2.11,2.07,2.06,08,1.82,2.00,2.13,1.85,2.15,1.73]
var sound = document.getElementById("alert_sound");
if (Math.min(...arduino) < 5) {
    const playPromise = sound.play();
    if (playPromise !== null) {
        playPromise.catch(() => { sound.play(); })
    };

I found the final 4 lines of the js as an answer somewhere else that I thought would work, but it turned out fruitless too.


Solution

  • It's because of Chrome's new Audio policy.

    As you can see in the example below, the audio won't really start to play until you click that non-sensical click me button. Google Chrome's new Audio Play policy says, the user first has to interact with the document for audios to get played. Read more about it here.

    var sound = document.getElementById("sound");
    
    setInterval(() => sound.play(), 3000)
    <audio id="sound" controls>
       <source src="https://www.w3schools.com/jsref/horse.ogg" type="audio/ogg">
    </audio>    
    
    <button>Click me to do nothing</button>