Search code examples
javascriptvideohtml5-videomime-typescodec

How to get mp4's codec mime information?


How can I get a MP4's codec information in JavaScript so that I can check if the browser supports it?

const audioCodec = '';//<---?? exmaple: "mp4a.40.2"
const videoCodec = '';//<---?? example: "avc1.42e01e"
const video = document.getElementById('video');
const mimeCodec = 'video/mp4; codecs="' + audioCodec + ', ' + videoCodec + '"';

if (!('MediaSource' in window) || !MediaSource.isTypeSupported(mimeCodec)) {
    console.error('Unsupported MIME type or codec: ', mimeCodec);
}


Solution

  • There is no built in way accessible to us, so you'd have to parse the files yourself, or use a library to do so.

    Among a lot of other features, MP4Box.js can do this for mp4 files.

    const mp4boxfile = MP4Box.createFile();
    mp4boxfile.onError = console.error;
    mp4boxfile.onReady = (info) => {
      console.log( info.tracks.map( track => track.codec ) );
    };
    fetch( "https://dl.dropboxusercontent.com/s/hyeredbcn60feei/BigChunksBunny1.mp4" ).then( (resp) => resp.arrayBuffer() )
      .then( (buf) => {
        buf.fileStart = 0;
        mp4boxfile.appendBuffer( buf );
        mp4boxfile.flush();
      } );
    <script src="https://gpac.github.io/mp4box.js/dist/mp4box.all.js"></script>

    They apparently also have a "simple" build which may be enough for your use case.