snippet Thursday 25 April 2024

Dynamically create audio elements with JavaScript

Author

Sometimes you need music to play and pause without an actual player. Use this code to dynamically create audio elements as well as pause and play them

// Create Element and play it
var audioElement = document.createElement("audio");
audioElement.setAttribute("src", "assets/pathtofile.mp3");
audioElement.play();

// If you want to pause
audioElement.pause();