简体   繁体   中英

I cant stop currently playing audio on served webpages via ajax calls

I have designed a pub quiz page which all works as I wanted. For the audio round I want to play a sound that all the players will hear. That works. But when I click stop, it stops in my browser instance and not in the players pages.

I am using txt files generated by PHP from the quiz masters page. Using ajax to read these files every second and change the output when its changed on the players page. All my code works, even can trigger new sound events. But once an audio event is playing in the players browser, I just can not stop it. My php is creating the text files - blank entry when stop is clicked. When I change the text file a new audio clip does play. I tried adding aud.stop(); at the beginning of the call but it prevents any audio playing.

<script>
function updateq(){
    $.ajax({url: '<?php echo $baseurl."curquestion.txt"; ?>',  ifModified: true, success: function(result, status){
    if (status === 'success') { $('#cq').html(result); }
    }});
    $.ajax({url: '<?php echo $baseurl."playaudio.txt"; ?>',  ifModified: true, success: function(result, status){
    if (status === 'success') { var aud = new Audio(result);    aud.play();
    }
   }});
    setTimeout('updateq()',1000);
};
</script>
<script type="text/javascript">  
$(document).ready(
function() 
    {
     updateq();
    });
</script>

When my playaudio.txt changes from a valid mp3 file name to "" I was hoping the audio would stop. But once triggered in the players web browser, once an audio file is played it plays til completion or until page refresh. The audio events seem to overlap whilst the webpage is loaded.

I think the issue is is scope. The var that plays your audio doesn't exists upon loading the next one so you can't stop it. Maybe try something like this.

<script>
var lastAud = null;
function updateq(){
    $.ajax({url: '<?php echo $baseurl."curquestion.txt"; ?>',  ifModified: true, success: function(result, status){
    if (status === 'success') { $('#cq').html(result); }
    }});
    $.ajax({url: '<?php echo $baseurl."playaudio.txt"; ?>',  ifModified: true, success: function(result, status){
    if (status === 'success') {
      if(lastAud && lastAud.src != result) {
           location.reload();
      }

      aud = new Audio(result);
      aud.play();
      lastAud = aud;
    }
   }});
    setTimeout('updateq()',1000);
};
</script>
<script type="text/javascript">  
$(document).ready(
function() 
    {
     updateq();
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM