Last active
February 3, 2026 10:16
-
-
Save devhammed/17634a680ea9e9c76b6523aa3367cc3d to your computer and use it in GitHub Desktop.
Get Media File Duration In Seconds (With Low-Budget Caching)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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