Categories
JavaScript Answers

How to change audio element src with JavaScript?

Spread the love

Sometimes, we want to change audio element src with JavaScript.

In this article, we’ll look at how to change audio element src with JavaScript.

How to change audio element src with JavaScript?

To change audio element src with JavaScript, we set the element’s src attribute.

For instance, we write

const audio = document.getElementById("audio");

const source = document.getElementById("audioSource");
source.src = elm.getAttribute("data-value");

audio.load();
audio.play();

to select the audio element with getElementById.

Then we get the element with the data-value attribute with getElementById.

We use the data-value attribute value for the src attribute’s value.

Next we call load to preload the audio element with the clip from the new URL.

Then we call play to play it.

Conclusion

To change audio element src with JavaScript, we set the element’s src attribute.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *