Detect Unsupported Audio Formats in an HTML Player

A playable container does not guarantee that the browser supports the codec inside it. Declare the complete MIME type, test it with canPlayType(), and still listen for loading errors because server headers or file contents may be wrong.

Last updated: November 1, 2026.

<audio id="player" controls>
  <source src="episode.m4a" type='audio/mp4; codecs="mp4a.40.2"'>
</audio>
<p id="audio-status" role="status"></p>

<script>
const player = document.querySelector('#player');
const status = document.querySelector('#audio-status');
const source = player.querySelector('source');

if (player.canPlayType(source.type) === '') {
  status.textContent = 'This browser does not support this audio format.';
} else {
  source.addEventListener('error', () => {
    status.textContent = 'The audio file could not be loaded.';
  });
  player.load();
}
</script>

canPlayType() returns an empty string for a type the browser cannot play, maybe when support is uncertain, or probably when playback is expected. It is a capability hint, not proof that the URL is valid.

Describe the codec, not only the container

The HTMLMediaElement reference documents canPlayType() and the media error state. A file ending in .m4a or .mp4 can contain different audio codecs, so use the actual codec string produced by your encoder.

Offer multiple <source> elements when practical. The browser evaluates them in order. The <source> documentation recommends an accurate type attribute so unsupported choices can be skipped without downloading them.

Check delivery as well as codec support

A supported type can still fail because the URL returns HTML, requires credentials, blocks cross-origin access, or sends an incorrect Content-Type. Inspect the Network panel for status, response headers, and the first response bytes. Do not assume that a rejected play() promise means an unsupported codec; autoplay policy can reject playback too.

Continue with understanding HTTP content types, tracing browser errors, and the HTML reference.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov