From 738d45616b2956b85b60b07fce1c3d6f26fcd0e8 Mon Sep 17 00:00:00 2001 From: sujal-into Date: Fri, 22 Nov 2024 18:01:11 +0545 Subject: [PATCH] fix: function to get the video duration --- packages/utils/video/index.ts | 42 +++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/utils/video/index.ts b/packages/utils/video/index.ts index a31bfdad58..65f69f3b5a 100644 --- a/packages/utils/video/index.ts +++ b/packages/utils/video/index.ts @@ -1,3 +1,5 @@ +import MP4Box, { MP4ArrayBuffer, MP4BoxFile, MP4FileInfo } from "mp4box"; + import { VideoFileMetadata } from "../types/files"; const getVideoDuration = (file: File) => { @@ -19,11 +21,47 @@ const getVideoDuration = (file: File) => { } catch (e) { console.error("Fail to get video duration: ", e); } + + return duration; +}; + +export const getVideoDurationFromBuffer = async (buffer: ArrayBuffer) => { + let duration = 0; + const mp4boxFile: MP4BoxFile = MP4Box.createFile(); + + mp4boxFile.onReady = (info: MP4FileInfo) => { + const durationInSec = info.duration / info.timescale; + duration = durationInSec * 1000; + }; + + const fileData = buffer.slice(0); + (fileData as MP4ArrayBuffer).fileStart = 0; + mp4boxFile.appendBuffer(fileData); + + return duration; +}; + +export const getVideoDurationFromURL = async (url: string) => { + let duration = 0; + + try { + const response = await fetch(url, { + method: "GET", + }); + const buffer = await response.arrayBuffer(); + + duration = await getVideoDurationFromBuffer(buffer); + } catch (error) { + console.log(error); + } + return duration; }; -export const getVideoData = (file: File): VideoFileMetadata => { - const duration = getVideoDuration(file) * 1000; +export const getVideoData = async (file: File): Promise => { + const fileBuffer = await file.arrayBuffer(); + const duration = await getVideoDurationFromBuffer(fileBuffer); + return { duration, };