I've been attempting to switch the audio file when a button is clicked but I keep encountering this error
Uncaught TypeError: audio.load is not a function
Below is my code, where the goal is to change the audio file upon pressing the button.
If I remove the audio.load()
line, the code runs and the src
updates, however, the audio itself does not change. What am I overlooking?
HTML:
<!DOCTYPE HTML>
<html>
<body>
<br>
<audio controls id="audio">
<source src = "audio_file_1.mp3"
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, for those looking for sample sound files to use in place of audio_file_1.mp3
and audio_file_2.mp3
, feel free to suggest them so that others can easily test the code)
Edit Regarding Rob M's Answer:
For individuals facing the same issue, the solution involves modifying two lines:
Firstly, in the HTML code, change <audio control>
to
<audio control id="audio_id">
Secondly, in the javascript code, replace audio.load()
with
document.getElementById('audio_id').load();