Create an Audio Element - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Audio

Introduction

You can create an <audio> element by using the document.createElement() method:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">create an AUDIO element in a .mp3 or .ogg file format</button>

<script>
function myFunction() {/*  www  .  j  a va  2 s. co  m*/
    var x = document.createElement("AUDIO");

    if (x.canPlayType("audio/mpeg")) {
        x.setAttribute("src","your.mp3");
    } else {
        x.setAttribute("src","your.ogg");
    }

    x.setAttribute("controls", "controls");
    document.body.appendChild(x);
}
</script>

</body>
</html>

Related Tutorials