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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With