Check Supported Audio Formats with JavaScript

As streaming turns into our fundamental enjoyment source and providers combat to create the quality video layoutit’ll be increasingly essential that we hit upon device and browser video aid before posting films on our websites.

// Create an audio element so we can use the canPlayType method
const audio = document.createElement('audio');

// Does the device support mp3?
audio.canPlayType('audio/mpeg'); // "probably"

There are three possible outcomes from canPlayType:

possibly“: The media kind appears to be playable
maybe“: can’t inform if the media kind is playable without gambling it
“”: The media kind isn’t always playable
we are able to create a feature much like my supportsVideoType function to make audio detection easy:

function supportsAudioType(type) {
  let audio;

  // Allow user to create shortcuts, i.e. just "mp3"
  let formats = {
    mp3: 'audio/mpeg',
    mp4: 'audio/mp4',
    aif: 'audio/x-aiff'
  };

  if(!audio) {
    audio = document.createElement('audio')
  }

  return audio.canPlayType(formats[type] || type);
}

// Usage
if(supportsVideoType('mp3') === "probably") {
  // Set the video to mp3
}
else {
  // Set the video to wav or other format
}

Taking the time to detect area audio and video codecs are well worth it, permitting you to deliver clearer media with better compression to enhance load time. maintain those JavaScript capabilities in mind to your big or small media site!

 

Please follow and like us:



Leave a Comment

Your email address will not be published. Required fields are marked *