Skip to content

Instantly share code, notes, and snippets.

@Shuumatsu
Last active May 2, 2018 07:15
Show Gist options
  • Save Shuumatsu/7fe331ce681cd604f8dde3152513e471 to your computer and use it in GitHub Desktop.
Save Shuumatsu/7fe331ce681cd604f8dde3152513e471 to your computer and use it in GitHub Desktop.
const cache = new Map()
export default src =>
new Promise((resolve, reject) => {
if (cache.has(src)) resolve(cache.get(src))
const audio = document.createElement('audio')
audio.addEventListener('loadedmetadata', () => {
const duration = audio.duration
// Along comes Chrome
// Unfortunately, there is currently a Chromium bug that causes the duration not to be available under certain circumstances. In these conditions, you will see the video or audio duration as being Infinity (a vestige of the infinite stream concept, presumably).
if (duration === Infinity) {
const ontimeupdate = () => {
const duration = audio.duration
cache.set(src, duration)
resolve(duration)
audio.currentTime = 0
audio.removeEventListener('timeupdate', ontimeupdate)
}
audio.addEventListener('timeupdate', ontimeupdate)
audio.currentTime = 1e101
return
}
cache.set(src, duration)
resolve(duration)
})
audio.addEventListener('error', reject)
audio.src = src
})
// http://victorblog.com/2018/02/14/get-video-and-audio-blob-duration-in-html5/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment