Javascript DOM HTML Audio Object create

Introduction

The Audio object represents an HTML <audio> element.

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

var x = document.createElement("AUDIO");

Click the button to create an AUDIO element.

It can play a sound in a .mp3 or .ogg file format.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {/*  w ww  .j a v a2s .com*/
  var x = document.createElement("AUDIO");

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

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

</body>
</html>



PreviousNext

Related