Initial commit
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
// 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'));
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user