Search code examples
javascriptaudio

How to play audio at a specific time in javascript


Heres what ive got, but i cant seem to auto update the time?

<script>
function updateTime(){
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
}
setInterval(updateTime, 1000);
var audio = new Audio('audio.mp3');`enter code here`
if(minutes === 39){
audio.play();
}
</script>

So im trying to create a web app that will play an audio file at a specific time of the day, also is there anyway of stopping the sound at another time? say 5 mins later?


Solution

  • As adeneo's comment states, you need to have the conditional statement within the event function.

    The following will call updateTime every second, and if the minute of the day is 39 and it is not playing, it will start playing audio. It will also call setTimeout to stop the audio five minutes later.

    Feel free to add the hour within the if statement if you like.

    var audio = new Audio('audio.mp3');
    
    function updateTime(){
      var currentTime = new Date();
      var hours = currentTime.getHours();
      var minutes = currentTime.getMinutes();
    
      if (minutes == 39 && audio.paused) {
         audio.play();
         setTimeout(function() { audtio.pause(); }, 300000);
      }
    }
    
    setInterval(updateTime, 1000);