简体   繁体   中英

Audio files (.mp3) don't play on page reload, only once when VS code/Live Server extension auto-reloads on save

Tested on Chrome/Firefox/Edge. I'm working on Win10 with VS code and the "Live Server" extension.

The page loads, first audio file(.mp3) plays, then different elements appear with Jquery delays, etc. Upon a certain < ul > fading in, the second audio file plays.

With "Live Server" 's auto-reloading on save feature or by clicking on my navbar's link to the same page (testing purposes), the sounds and Jquery functions work fine, but if I refresh with the browser itself, the sound files don't play again.

I tried solutions found on google, like setting currentTime, onLoad, but they didn't really answer a similar problem, the most success I've had was achieving the same results I had from the start.

I'm just starting to learn JS and Jquery, so I'm sorry if the code is messy.

  <script type="text/javascript" src="script/jquery-3.5.1.min.js"></script>

  <script type="text/javascript" src="script/main.js"></script>

  <script>
      var audio1 = $("#mantra")[0];
      var audio2 = $("#wind")[0];
      audio1.play()
        

    $("document").ready(function () {
      $(".choix").hide()   // .choix is the class of fig1, fig2, fig3, fig4
      $("#fig1").delay(9500).fadeIn(3000);
      $("#fig2").delay(9550).fadeIn(3000);
      $("#fig3").delay(9600).fadeIn(3000);
      $("#fig4").delay(9650).fadeIn(3000);
      
      $("#tagline").hide().delay(2000).fadeIn(1500)
          .delay(1500).fadeOut(2000).queue(function(n) {
          $(this).html("<br> Start here");
          n();
        }).delay(700).fadeIn(2000);
      
      $(".textNav").hide().delay(800).fadeIn(1500);

      });
      $("#wind").stop("true").delay(9400).queue(function() {  //9400ms delay to start just before fig1+
        audio2.play()
      });

      
    });
  </script>

In cases when the audio is not playing, check the console and you will find an error stating

DOMException: play() failed because the user didn't interact with the document first.

This is because browsers don't allow music autoplay on page-load. It is necessary for the user to make some interaction (click, tap, etc.) with the window before playing the audio.

Source

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