2

I have an audio file called sound.wav that is 14 seconds long. When a user clicks a button, sound.wav source url is changed and sound.wav is reloaded and is now 7 seconds long.
However, my browser does not display the changes. Only after clicking the refresh button does it display the changes.

Here is my code:

  <div id="audioContainer">
    <audio id ="myAudio" controls>
      <source id = "wav_src" src="http://localhost:3000/sounds/sound.wav" type="audio/wav">
    </audio>
  </div>
//user clicks button... sound.wav's url source is changed
  document.getElementById("myAudio").load();   //code to reload the sound.wav  

As you can see, I'm reloading the html audio element for sound.wav after the user presses a button. However, the sound file remains unchanged on the website, unless I hit refresh.

How do I fix this?

James Jones
  • 3,850
  • 5
  • 25
  • 44
Karliene
  • 147
  • 1
  • 3
  • 10
  • Where is the `//code to reload the sound.wav`? Is it this `load()` function? – deEr. May 15 '18 at 08:41
  • Are you intentionally changing the duration? Or do you have different wav files? – zer00ne May 15 '18 at 08:51
  • Since you are using a `` element, you must call the ` – Kaiido May 15 '18 at 09:02
  • That's a dupe of https://stackoverflow.com/questions/32168173/success-change-source-track-of-video-use-onclick-button-but-the-video-still-s/32176019#32176019 which doesn't have an upvoted answer... – Kaiido May 15 '18 at 09:04
  • Maybe this helps: https://stackoverflow.com/questions/25821915/how-to-force-the-html5-audio-tag-to-reload-a-changing-file , especially Alex P's answer. – WJH Jun 08 '23 at 08:00

1 Answers1

1

When you change the src of the <source> element, it doesn't change the src of the its parent MediaElement (<audio> or <video>). You have to call this MediaElement's .load() method :

set_src.onclick = function() {
  source.src = 'http://cdn.music2ten.com/mp3/pd4u/GershwinWhiteman-RhapsodyInBluePart1.mp3';
  console.log('source src:', source.src);
  setTimeout(function(){console.log('audio src:', audio.currentSrc)});
}

load_btn.onclick = function() {
  audio.load(); // you must call this
  setTimeout(function(){console.log('audio src:', audio.currentSrc)});
};
<audio id="audio" controls="controls">
  <source id="source">
</audio>
<br>
<button id="set_src">set src</button>
<button id="load_btn">load</button>

Of course you would normally do this in one-go:

set_src.onclick = function() {
  source.src = 'http://cdn.music2ten.com/mp3/pd4u/GershwinWhiteman-RhapsodyInBluePart1.mp3';
  audio.load(); // you must call this
}
<audio id="audio" controls="controls">
  <source id="source">
</audio>
<br>
<button id="set_src">set src</button>
Kaiido
  • 123,334
  • 13
  • 219
  • 285