Eric HB
Eric HB

Reputation: 887

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();

Upvotes: 2

Views: 4089

Answers (2)

AngeLOL
AngeLOL

Reputation: 116

Well, I think you are trying to access to <audio> element by its id attribute, but you haven't set id attribute to audio tag. It must be something like this

<audio id="audio" controls>
    <source src = "audio_file_1.mp3"
      id="track" type="audio/mpeg">
      Your browser does not support the audio element!
</audio>

And changing audio file:

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

changeAudio();

Upvotes: 0

Rob M.
Rob M.

Reputation: 36511

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.

Upvotes: 4

Related Questions