vue上传组件获取音频时长

1,117 阅读1分钟

之前在做公司一个项目需求的时候,需要获取批量上传的音频的时长,顺便整理一下在写完这个上传控件后的一点心得。

//上传的控件
<a-upload
    list-type="picture-card"
    class="avatar-uploader"
    :custom-request="customRequest"
    accept=".mp4,.mov,.m4v'"
    :file-list="file_list"
    :before-upload="beforeUpload"
    @preview="handlePreview"
    @change="handleChange"
  >
    <div v-if="file_list.length < 1">
        <a-icon type="plus"></a-icon>
        <div class="ant-upload-text">上传文件</div>
    </div>
  </a-upload>

1.使用addEventListener(),向指定元素添加事件句柄。

使用addEventListener方法,可以在两种状态中获取时长,第一种是在change事件中进行,第二张是在上传前的钩子函数中进行。

//获取时长的函数
getTimes(file) {
    let url = URL.createObjectURL(file)
    let audioElement = new Audio(url)

    return new Promise((resolve, reject) => {
        audioElement.addEventListener('loadedmetadata', function() {
            resolve(parseInt(audioElement.duration))
        })
    })
},
1.1 change,上传文件改变状态时获取duration
handleChange(info) {
    this.file_list = info.fileList

    if (info.file.status === 'uploading') {
        this.getTimes(info.file.originFileObj).then(res => {
            info.file.duration = res
            info.fileList[0].duration = res//在这里给duration赋值
        })
    }

    if (info.file.status === 'done') {
        this.preview_url = info.file.response.url
        console.log(info)//在这里打印就看到duration
    }
},
1.2 beforeUpload,上传文件之前获取duration
beforeUpload(file) {
    return new Promise((resolve, reject) => {
        const isVideo = file.type === 'video/mp4' || file.type === 'video/mov'
        if (!isVideo) {
            this.$message.error('请选择视频上传!')
            return reject()
        }

        this.getTimes(file).then(res => {
            file.duration = res//在这里给duration赋值
            return resolve(true)
        })
    })
},
handleChange(info) {
    this.file_list = info.fileList

    if (info.file.status === 'done') {
        this.preview_url = info.file.response.url
        console.log(info)//在这里打印就看到duration
    }
},

2.利用已有的video元素获取时长。

在页面先写好一个video,在上传的时候填入上传链接,获取时长,但是这个方法个人觉得有点麻烦了,而且如果是多文件上传的时候,那就更麻烦了。

<video
    ref="preview_video"
    controls
    style="display: none"
    >
        你的浏览器不支持video
</video>   

在beforeUpload的时候获取上传的路径后填入video的地址上,上传成功后获取video的duration

beforeUpload(file) {
        const isVideo = file.type === 'video/mp4' || file.type === 'video/mov'
        if (!isVideo) {
            this.$message.error('请选择视频上传!')
        }

        let url = URL.createObjectURL(file)
        this.$refs.preview_video.src = url

        return isVideo
},
handleChange(info) {
    this.file_list = info.fileList

    if (info.file.status === 'done') {
        this.preview_url = info.file.response.url
        console.log(Math.floor(this.$refs.preview_video.duration))//获取时长
    }
},