前端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;
文章参考:https://www.jianshu.com/p/f1b714f1a9f8
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)