Skip to content

Commit

Permalink
fix: function to get the video duration
Browse files Browse the repository at this point in the history
  • Loading branch information
sujal-into committed Nov 22, 2024
1 parent 749be8b commit 738d456
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions packages/utils/video/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import MP4Box, { MP4ArrayBuffer, MP4BoxFile, MP4FileInfo } from "mp4box";

import { VideoFileMetadata } from "../types/files";

const getVideoDuration = (file: File) => {
Expand All @@ -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<VideoFileMetadata> => {
const fileBuffer = await file.arrayBuffer();
const duration = await getVideoDurationFromBuffer(fileBuffer);

return {
duration,
};
Expand Down

0 comments on commit 738d456

Please sign in to comment.