Detect if video has audio

Jonny Harris avatar
  • While working on the Web Stories for WordPress plugin and working on functionality to mute videos, there was a need to detect if a video already had audio or not. But doing some quick googling, I noticed there none of the answers I found online works well or at all. Worse yet, the answers were not written using modern javascript, either not using promises or using jQuery. So today, I am sharing this gist, in hopes that the next person who comes across this problem, has a workabout solution.

    function hasAudio(video) {
    return (
    video.mozHasAudio ||
    Boolean(video.webkitAudioDecodedByteCount) ||
    Boolean(video.audioTracks?.length)
    );
    }
    function hasVideoGotAudio(src) {
    const video = document.createElement('video');
    video.muted = true;
    video.crossOrigin = 'anonymous';
    video.preload = 'auto';
    return new Promise((resolve, reject) => {
    video.addEventListener('error', reject);
    video.addEventListener(
    'canplay',
    () => {
    video.currentTime = 0.99;
    },
    { once: true } // Important because 'canplay' can be fired hundreds of times.
    );
    video.addEventListener('seeked', () => resolve(hasAudio(video)), {
    once: true,
    });
    video.src = src;
    });
    }
    export default hasVideoGotAudio;