How to update <audio> html without having to refresh the entire page?

Asked

Viewed 588 times

0

My web page should play a different audio every 1 minute, without refreshing the entire page. The audio can stay in a div, but it needs to be updated every 1 minute, but the way it is, the browser always picks up the first audio played, and whenever I change the audio and save the file, the browser always picks up audio by which the page was last loaded.

In short, I need to update the audio in a div.

Follows my code:

HTML AND PHP

<?php

include("config/conn.php");
$seguntos=2; //segundos
?>  

<audio id="audio" style="display:none">
<source src="sons/aero.wav" type="audio/wav" /> <!--esse arquivo é modificado faço isso manual mesmo e salvo o arquivo, mas irei automatizar isso -->
</audio>

JAVASCRIPT AUDIO FUNCTION

<script type="text/javascript">

audio = document.getElementById('audio');

function play(){
audio.play();
audio.stop();
audio.pause();
}

</script>

JAVASCRIPT FUNCTION CHECKS THE SITUATION AND THE PLAY

<script type="text/javascript">

    function atualizar()
    {
        $.post('atualizapainel.php', function (paciente) {
            $('#paciente').html('<b>' + paciente.nome_paciente + '</b><br />');
            $('#local').html('<b>' + paciente.situacao + '</b><br />');

            if (paciente.situacao == 'EM ATENDIMENTO')  {
                play();

            } 
            paciente.situacao=1;
        }, 'JSON');
    }

    setInterval("atualizar()",  <?php echo $seguntos*30000; ?>); // Valor em milissegundos
    $(function() {
        atualizar();

    });

</script>

2 answers

1

Audio page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script language="javascript">

$( document ).ready(function() {
   update();
   play()
});

function update(){
setInterval(
    function() {
       //pega o valor do input a ser enviado via post para atualizaAudio.php
       var num = $("#idInput").val();
        $.ajax({
            url: "atualizaAudio.php",
            type: 'POST',
            data: {numAudio: num},
            success: function(n){
               //n é composto de uma url do audio mais o caractere | mais um numero
               //exemplo to_nem_ai.mp3|1
              //separamos o rtetorno da requisição dado por n
              var res = n.split("|");
              //aqui setamos o novo valor para o input dado por res[1]
              document.getElementById("idInput").value = res[1];
              //conteudo atualizado da div que contem o audio, setando o src do audio para o novo valor dado por res[0]
              document.getElementById("demo").innerHTML = '<audio id="audio"><source id="qqid" src="'+res[0]+'" type="audio/mpeg"></audio>';
              play();

            }
        });

    },

15000);
}

</script>

<input id="idInput" type="hidden" value="0">

<div id="demo">
<audio id="audio">
<source id="qqid" src="https://s3.amazonaws.com/Syntaxxx/bigger-picture.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>

<script language="javascript">
function play(){
var x = document.getElementById("audio"); 
   x.play();
}
</script>

updateAudio.php

//vindo via post
$numAudio=$_POST['numAudio'];

//array auxiliar com mumeração igual a quantidade de audios
$numero = array(1, 2, 3, 4);

//condicional que incrementa a variável $numAudio até a quantidade de áudios no array 
$numAudio < 4 ? $numAudio++ : $numAudio=1;

//seta o audio de acordo com a variável $numAudio
switch ($numAudio) {
    case 1:
        $audio="tarantella.mp3";
        break;
    case 2:
        $audio="esera.mp3";
        break;
    case 3:
        $audio="deo.mp3";
        break;
    case 4:
        $audio="to_nem_ai.mp3";
        break;
    default:
        $audio="https://s3.amazonaws.com/Syntaxxx/bigger-picture.mp3";
}

//resultado a passar para processar na pagina do audio
echo $audio."|".$numAudio;

As a developer, you can change the behavior of Google Chrome’s auto-play policy locally to test your website.

You can choose to completely disable the auto-play policy by setting the Chrome flag "Autoplay Policy" for "No user Gesture is required" in Chrome://flags/#autoplay-policy . This allows you to test your website as if the user was heavily involved with your site and automatic playback was always allowed.

inserir a descrição da imagem aqui

Changes to Auto Play Policy (english)

Google translator - Automatic Playback Policy Changes

0

Without refreshing the page, you need to update the whole element audio.

Do the following, include the audio in a span with a id:

<span id="audiocontainer" style="display:none">
   <audio id="audio">
      <source src="sons/aero.wav" type="audio/wav" />
   </audio>
</span>

In function play(), change the HTML of span with HTML itself, causing the browser to pull the file again wav, but you also need to modify the file name. You don’t need to change the original name, just add some parameter to make the browser think it’s a new file, something like sons/aero.wav?12321321.

To generate this parameter you can use the system date. See the code:

audio = document.getElementById('audio');

function play(){
   var src = "sons/aero.wav";
   var param = new Date().getTime();
   src += "?"+param;
   $("#audio source").attr("src", src);
   $("#audiocontainer").html($("#audiocontainer").html());

   audio.play();
   audio.stop();
   audio.pause();
}
  • This audio tag does not work with style="display:None" nor does it automatically play in Chrome and Opera. Safari does not work at all.

  • pq vc denied my answer?

  • It was not me. rss

  • Since it wasn’t you, why do you think they did? see AP’s question Minha pagina web deve tocar um audio diferente a cada 1 minuto, sem dar refresh na pagina inteira.

  • Xiii, I think I figured it out, it was supposed to be a minute and I put 15 seconds, Aff

  • I have no idea. There are people out there who are really negative.

  • I got that, I feel sorry for them!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.