35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
// utils/getVideoDuration.ts
|
|
export async function getVideoDuration(file: File): Promise<number> {
|
|
return new Promise((resolve, reject) => {
|
|
// create an object URL for the file
|
|
const url = URL.createObjectURL(file);
|
|
const video = document.createElement('video');
|
|
|
|
// Make sure it doesn't try to load UI, just metadata
|
|
video.preload = 'metadata';
|
|
video.src = url;
|
|
|
|
const cleanup = () => {
|
|
URL.revokeObjectURL(url);
|
|
video.removeAttribute('src');
|
|
video.load();
|
|
};
|
|
|
|
video.addEventListener('loadedmetadata', () => {
|
|
// duration in seconds (float)
|
|
const duration = video.duration;
|
|
cleanup();
|
|
// Some encodings return Infinity — guard that
|
|
if (!isFinite(duration) || duration <= 0) {
|
|
return reject(new Error('Could not determine duration'));
|
|
}
|
|
resolve(Math.round(duration)); // return integer seconds
|
|
});
|
|
|
|
video.addEventListener('error', (e) => {
|
|
cleanup();
|
|
reject(new Error('Error reading video metadata'));
|
|
});
|
|
});
|
|
}
|