How to update audio html without refreshing the entire page?

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 mute the audio and save the file, the browser always which page was uploaded the last time.

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

Follow 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>

AUDIO JAVASCRIPT FUNCTION

<script type="text/javascript">

audio = document.getElementById('audio');

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

</script>

JAVASCRIPT FUNCTION VERIFIES SITUATION AND 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>
    
asked by anonymous 09.06.2018 / 14:27

2 answers

0

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

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 the play() function, change the HTML of span with HTML itself, causing the browser to pull the wav file again, but you must also modify the file name. You do not need to change the original name, just add any parameter so the browser thinks 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();
}
    
09.06.2018 / 17:25
0

Audio Page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptlanguage="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 the Chrome autoplay policy locally to test your website.

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

Automatic Playback Policy Changes (English)

Google translator - Changes to AutoPlay Policy

    
09.06.2018 / 22:46