javascriptjqueryhtmlajax

How do I fix audio not always autoplaying


Sometimes the autoplay doesn't work. This is set to play a song automatically and refresh the page to get the next song because I couldn't figure out how to get it to call my php again and get a new song. It always works when you click play. It just doesn't do like it should and autoplay.

Why does autoplay sometimes not work?

The error from console when autoplay doesn't work:

Uncaught (in promise) DOMException line 26:
        25  $('audio').get(0).load();
        26  $('audio').get(0).play();
        27  document.getElementById("songName").innerHTML = 

'http://192.168.1.180' + data;

An error that always appears on page load:

Uncaught ReferenceError: url is not defined
    at radio.html:15
            14  <br />
            15  <script>document.write(url);</script>
            16  <button onclick="skip()">Skip me</button>

Example of input given through ajax when it happens:

http://192.168.180/uploads/Music/Ive_Gone_Away_Black_Label_Society_Catacombs_of_the_Black_Vatican_2014.mp3

 <html>
    <head></head>
    <body>
      <center>
        <?php echo $data ?>
        <audio id="playMusic" controls autoplay>
          <source id="source" src="" type="audio/mp3">
          Your browser does not support the audio element.
        </audio>
        <br />
        <button onclick="skip()">Skip me</button>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script type="text/javascript">
          $.ajax({
            url: 'radio.php',
            data: { attr1: 'value1' },
            success: function (data) {
              console.log(data);
              $('audio #source').attr('src', data);
              $('audio').get(0).load();
              $('audio').get(0).play();
            }
          });
          playMusic.onended = function () {
            window.location.reload();
          };
          function skip() {
            window.location.reload();
          }
        </script>
      </center>
    </body>
    </html>


Solution

  • āŒ Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

    The answer is, it worked fine. It's just blocked by chrome itself.