Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update src but play previous file

I want to play music when the user clicks the div, however, when the user clicks the div the src changes, but the audio tag still plays the previous file

Here is the code

function music1() {
  document.getElementById("audiosrc").src = "j.mp3";
}
<audio controls id="audio" loop autoplay>
<source id="audiosrc" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/new_year_dubstep_minimix.ogg" type="audio/ogg">Your browser dose not Support the audio Tag
</audio>
like image 297
moji Avatar asked Mar 07 '26 01:03

moji


1 Answers

You have to load the new src to the audio element. Using .load() function solves this.

function changeSrc() {
  const audio = document.getElementById("audio");
  const source = document.getElementById("audiosrc");
  source.src = "https://www.myinstants.com/media/sounds/yeah-boymp4.mp3"
  audio.load();
}
<audio controls id="audio" loop autoplay>
  <source id="audiosrc" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/new_year_dubstep_minimix.ogg" type="audio/ogg">
Your browser dose not Support the audio Tag
</audio>

<button onclick="changeSrc()">change src</button>
like image 128
Sølve Tornøe Avatar answered Mar 08 '26 15:03

Sølve Tornøe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!