Search code examples
javascripthtmlnode.jsaudiobrowser-cache

Play button in HTML form not playing the latest audio file, plays an old version that is meant to have been overwritten


I have built a webpage that sends the text entered in a form to a Node.js server that synthesizes an audio file speech.wav and stores it in /public folder. When I go to localhost:8000 and the page loads for the first time, I can enter text, submit, and click on the play button to play the correct audio. Script for playing the file is

function playAudio() {
  var audioFile = new Audio('./speech.wav');
  audioFile.play()
}

Code for Play button is

          <div class="d-grid col-3">
            <button type="button" value="sound" class="btn btn-secondary" onclick="playAudio()"
              id="playbutton">Play</button>
          </div>

But when I enter some different text in the same page for the second time and submit, pressing the play button plays the old speech again and again. However, I noticed that the server correctly synthesized and stored the new speech audio in speech.wav, deleting the previous one. (I checked by going to the directory and playing it with Windows media player.) Opening another tab and going to localhost:8000 and straightaway clicking the play button surprisingly plays the new speech! But in the previous tab it would still play the old speech. I have tried this on Chrome, Edge and Chrome for android.

I am unable to pinpoint where this bug arises.


Solution

  • Most likely it's a caching issue, you can resolve like this:

    function playAudio() {
      var audioFile = new Audio('./speech.wav?' + new Date().getTime());
      audioFile.play()
    }
    

    As @fdcpp mentions below, using the private mode of your browser during development will eliminate caching issues. However in production (if you are changing the file while keeping the name the same) the ?time method is a quick fix