Eric HB Eric HB - 3 years ago 83
Javascript Question

Change audio file on button click

I am trying to change the audio file on a button click and am getting the error


Uncaught TypeError: audio.load is not a function


My code is below, the idea is to press the button and then the audio file will change.

Without the
audio.load()
line, the code will run and the
src
will update, but the audio does not change. What am I missing?

HTML:

<!DOCTYPE HTML>
<html>
<body>
<br>
<audio controls>
<source src = "audio_file_1.mp3"
id="audio" type="audio/mpeg">
Your browser does not support the audio element!
</audio>
<br>
<button onClick="changeAudio();">Change</button>
</body>
<script src="temp.js"></script>
</html>


Javascript:

// temp js
var a = 1;
function changeAudio() {
var audio = document.getElementById('audio');
if (a==1) {
audio.src = 'audio_file_1.mp3';
a = 2;
}
else {
audio.src = 'audio_file_2.mp3';
a = 1;
}
audio.load();
}

changeAudio();


(also, if anyone knows example sound files that I can use instead of the
audio_file_1.mp3
and
audio_file_2.mp3
, I would be happy to update the code so anyone can run it more easily)




Edit WRT Rob M's answer:

For anyone with the same problem, the solution is to change two lines:

First, in the HTML code, the
<audio control>
should turn to
<audio control id="audio_id">


Second, in the javascript code the
audio.load()
should turn to
document.getElementById('audio_id').load();

Answer Source

There is no .load() event on a <source> tag, it is on the <audio> tag - update your code to call load() on the parent <audio> tag and it should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download