Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active February 3, 2026 10:16
Show Gist options
  • Select an option

  • Save devhammed/17634a680ea9e9c76b6523aa3367cc3d to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/17634a680ea9e9c76b6523aa3367cc3d to your computer and use it in GitHub Desktop.
Get Media File Duration In Seconds (With Low-Budget Caching)
/**
* Get media file duration in seconds.
*/
export function getMediaDuration(file: File): Promise<number> {
if (!window.getMediaDurationCache) {
window.getMediaDurationCache = new WeakMap();
}
const cached = window.getMediaDurationCache.get(file);
if (cached !== undefined) {
return Promise.resolve(cached);
}
return new Promise(resolve => {
const isVideo = file.type.startsWith('video/');
const media = document.createElement(isVideo ? 'video' : 'audio');
const objectUrl = URL.createObjectURL(file);
media.preload = 'metadata';
media.src = objectUrl;
media.onloadedmetadata = () => {
const duration = media.duration;
URL.revokeObjectURL(objectUrl);
media.remove();
window.getMediaDurationCache.set(file, duration);
resolve(duration);
};
media.onerror = e => {
URL.revokeObjectURL(objectUrl);
media.remove();
console.error(e);
resolve(0);
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment