Karliene
Karliene

Reputation: 157

HTML: Audio file not updating when reloaded

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?

Upvotes: 2

Views: 3155

Answers (1)

Kaiido
Kaiido

Reputation: 136986

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>

Upvotes: 2

Related Questions