How to play an mp3 every x minutes when entering a page

2

I'm making a player where several music sounds and I want every x minutes, apart from the player, to play a single music without touching any button, only when entering the page, and in those x minutes the music sounds , right now just touching a button sounds, but I want it to sound in those x minutes, and then sound again every x minutes, that is I have to do a setInterval() but I do not know where to place it, I attach my code so that it looks better:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script>
    window.onload=function(){

        // creamos el objeto audio
        var audioElement = document.createElement('audio');

        // indicamos el archivo de audio a cargar
        audioElement.setAttribute('src', 'mimusica.mp3');


        document.getElementById("play").addEventListener("click", function() {
            // Si deseamos que inicie siempre desde el principio
            //audioElement.currentTime = 0;

            // iniciamos el audio
            audioElement.play();
        });

        document.getElementById("pause").addEventListener("click", function() {
            // hacemos pausa
            audioElement.pause();
        });
    };
    </script>
</head>
<body>

<div>
    <input type="button" value="Play" id="play">
    <input type="button" value="Pause" id="pause">
</div>

</body>
</html>

I want it to sound automatically in x minutes, and then repeat again in those x minutes

    
asked by Juanse Portillo 09.11.2018 в 15:18
source

1 answer

2

As you say, you could add a setInterval () This function executes what you define every x time in milliseconds. In your case I would call it like this:

setInterval(function(){audioElement.play();},30000);

We define the function we want to execute audioElement.play(); and then we tell you how often.

If we want to stop executing the interval, it is enough to assign it an id and then stop it:
let intervalo;

intervalo = setInterval(function(){audioElement.play();},30000);

clearInterval(intervalo);

If you want to do it like that, you do not need to call the interval before, just define it and assign it to a variable you already have.

In summary, your JavaScript would be something like this:

<script>
  window.onload=function(){
    // creamos el objeto audio
    var audioElement = document.createElement('audio');

    // indicamos el archivo de audio a cargar

    document.getElementById("play").addEventListener("click", function() {
        // Si deseamos que inicie siempre desde el principio
        //audioElement.currentTime = 0;

        // iniciamos el audio
        audioElement.play();
    });

    document.getElementById("pause").addEventListener("click", function() {
        // hacemos pausa
        audioElement.pause();
    });

    //se reproduce mi archivo cada 30 segundos
    setInterval(function(){audioElement.play();},30000);
  };
</script>
    
answered by 09.11.2018 / 15:34
source