How to Create a New Audio Element in JavaScript?

Estimated read time 1 min read

To create a new audio element in JavaScript, you can use the following code:

var audio = new Audio();
audio.src = "your-audio-file.mp3";
audio.controls = true;
audio.loop = false;
audio.autoplay = false;
document.body.appendChild(audio);

The above code creates a new audio element and sets its source to the specified audio file. The controls property is set to true to show the default audio controls in the browser. The loop property is set to false to prevent the audio from looping. The autoplay property is set to false to prevent the audio from automatically playing when the page loads. Finally, the audio element is added to the body element of the document by using appendChild.

You can also modify the audio element’s properties after it has been created, for example:

audio.volume = 0.5;
audio.currentTime = 10;

The above code sets the volume of the audio to 50% and seeks to 10 seconds into the audio file.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply