Get video duration when input a video file

前端 未结 3 652
忘掉有多难
忘掉有多难 2020-11-27 02:37

I\'m doing a project with HTML and Javascript that will run local with local files. I need to select a file by input, get its information and then decide if I\'ll add to my

3条回答
  •  独厮守ぢ
    2020-11-27 03:34

    Here is async/await Promise version:

    const loadVideo = file => new Promise((resolve, reject) => {
        try {
            let video = document.createElement('video')
            video.preload = 'metadata'
    
            video.onloadedmetadata = function () {
                resolve(this)
            }
    
            video.onerror = function () {
                reject("Invalid video. Please select a video file.")
            }
    
            video.src = window.URL.createObjectURL(file)
        } catch (e) {
            reject(e)
        }
    })
    

    Can be used as follows:

    const video = await loadVideo(e.currentTarget.files[0])
    console.log(video.duration)
    

提交回复
热议问题