@numairawan/video-duration
Version:
Get video duration from any url and video object in nodejs and browser.
1 lines • 1.13 kB
JavaScript
class VideoDuration{async analyze(e){if(this.isURL(e))try{let r=await fetch(e);if(!r.ok)throw Error(`Failed to download the video from the URL: HTTP ${r.status}`);let t=new Uint8Array(await r.arrayBuffer());return this.processVideoBuffer(t)}catch(i){console.error(i)}else if(e instanceof File&&this.isVideoFile(e)){let o=await this.readVideoFile(e);return this.processVideoBuffer(o)}else console.error("Invalid video source.")}processVideoBuffer(e){let r=new Uint8Array([109,118,104,100]),t=this.indexOfSequence(e,r)+16,i=this.readUInt32BE(e,t),o=this.readUInt32BE(e,t+4);return{ms:Math.floor(o/i*1e3),seconds:Math.floor(o/i),timeScale:i,duration:o}}isURL(e){try{return new URL(e),!0}catch(r){return!1}}isVideoFile(e){return e.type.startsWith("video/")}readVideoFile(e){return new Promise((r,t)=>{let i=new FileReader;i.onload=e=>{r(new Uint8Array(e.target.result))},i.onerror=e=>{t(e.error)},i.readAsArrayBuffer(e)})}readUInt32BE(e,r){return e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]}indexOfSequence(e,r){for(let t=0;t<e.length-r.length+1;t++){let i=!0;for(let o=0;o<r.length;o++)if(e[t+o]!==r[o]){i=!1;break}if(i)return t}return -1}}