前端input上传文件获取视频或音频的时长

1,424 阅读1分钟

前端input上传文件获取视频或音频的时长

背景

前端通过input上传视频或音频文件时,想同时获取视频或者音频文件的时长,核心是createObjectURL以及loadedmetadata

做法

前端通过input上传视频或音频文件时,想同时获取视频或者音频文件的时长的方法如下

import React, { Component, Fragment, createRef } from 'react';
import './Upload.less';

type StateType = {
  [propName: string]: any;
};

interface changeFileType {
  (e: any): any;
}

type PropType = {
  accept: string;
  changeFile: changeFileType;
  [propName: string]: any;
};

interface Upload {
  state: StateType;
  props: PropType;
  inputDom: any;
}

class Upload extends Component {

  constructor(props: any) {
    super(props);
    this.state = {
    };
    this.inputDom = createRef();
  }
  
  // 上传文件
  private changeFile = (e: any): void => {
    const file = e.target.files[0];
    if (!file.size) {
      return;
    }
    // 获取视频或音频的时长
    let duration: number = 0;
    if (file.type.indexOf('video') > -1 || file.type.indexOf('audio') > -1) {
      const url = URL.createObjectURL(file);
      const filelement = new Audio(url);
      filelement.addEventListener("loadedmetadata", function (_event) {
        duration = filelement.duration; // 得到视频或音频的时长,单位秒
        console.log('视频或音频的时长,单位秒', duration);
      });
    }
    const formData = new FormData();
    formData.append('file', file);
    
    const params = {
      file: formData,
      fileType: file.type,
      duration,
    };
    this.props.changeFile(params);
    this.inputDom.current.value = null;
  }

  render() {
    const { accept } = this.props;

    return (
      <Fragment>
        <input type="file" ref={this.inputDom} id="file" accept={accept} onChange={this.changeFile} className="file-input" />
      </Fragment>
    )
  }
}

export default Upload;

文章参考:www.jianshu.com/p/f1b714f1a…