Javascript DOM HTML Audio canPlayType() Method

Introduction

Check if your browser can play different types of audio:

View in separate window

<!DOCTYPE html> 
<html> 
<body> 

<p>Can my browser play OGG files? 
  <span>
    <button onclick="supportType(event,'audio/ogg','vorbis')" type="button">Test</button>
  </span>/*from  w  ww.j  a  v  a 2s  .c  om*/
</p>

<script> 
function supportType(e,vidType,codType) { 
  var x = document.createElement("AUDIO");
  isSupp = x.canPlayType(vidType+';codecs="'+codType+'"');
  if (isSupp == "") {
    isSupp = "No";
  }
  e.target.parentNode.innerHTML = "Answer: " + isSupp;
} 
</script> 
</body> 
</html>

The canPlayType() method checks if the browser can play a certain audio type.

The canPlayType() method can return one of the following values:

ValueMeaning
"probably" most likely supports this audio type
"maybe"might support this audio type
""(empty string) the browser does not support this audio type

Common values:

  • audio/mpeg
  • audio/ogg
  • audio/mp4

Common values, including codecs:

  • audio/ogg;codecs="vorbis"
  • audio/mp4;codecs="mp4a.40.5"

This method returns "probably" if codecs are included.




PreviousNext

Related