Home > database >  How to play sound every second in JavaScript without a trigger [duplicate]
How to play sound every second in JavaScript without a trigger [duplicate]

Time:10-07

I want to play audio every second as it is clock so wanted to insert a ticking sound .

Is there any way to achieve that without a trigger as clock should always be automatic .

Here is code which works on trigger and running:

<audio id="audiotag1" src="Sounds\clock tick.mp3" preload="metadata" controls></audio>
<button onclick="trigger()">Start</button>
function trigger(){
setInterval(clockRunner, 1000);
  function clockRunner(){
    var audioElement = document.getElementById('audiotag1');
    audioElement.play();
  }
}

Here is code which is without trigger but not running :

setInterval(clockRunner, 1000);

function clockRunner() {
  var audioElement = document.getElementById('audiotag1');
  audioElement.play();
}
<audio id="audiotag1" src="Sounds\clock tick.mp3" preload="metadata" controls></audio>

Error showing is :
Uncaught DOMException: play() failed because the user didn't interact with the document first.

Here is the question referring to the problem(Error) but solution provided is for video and they can be play muted and have visual content

Thanks for help in advance

CodePudding user response:

You cannot use document.getElementById (audio element) and js together to just use it and .play, that doesnt work, but this should

function play() {
var audio = new Audio('Sounds\clock tick.mp3');
audio.play();
}
setInterval(play, 1000)

In the string just use your source. :)

CodePudding user response:

I would like to say this is worth a shot

<audio id="audiotag1" preload="metadata" controls>
<source src="Sounds\clock tick.mp3" type="audio/mpeg"> 
</audio>
<button onclick="triger()">Start</button>

Also wanna mention you have a type, where it says audioElement.play you put an extra space, making it audioElement .play which could have thrown an error.

CodePudding user response:

Looks like there's a relevant post that just popped up. (Source: https://stackoverflow.com/a/62720714/9303612)

A couple of weeks ago I tried exactly what you intend to do, however, after a lot of research I realized this is nearly impossible now. For example in Chrome (I don't know if also in other browsers) you cannot autoplay sounds/videos unless one of these points is accomplished:

  • The user interacts with your website (click on any part of your site).
  • The user added your website to the home screen (mobile).
  • The user has crossed the media interaction index (MEI) threshold.
  • Your website is in the Google whitelist for autoplaying (such as Youtube).
  • Related