上传音频,限制音频大小

456 阅读1分钟

html

<el-upload
  id="audioUpload"
  class="avatar-uploader"
  action="/api"
  :headers="uploadHeaders"
  :show-file-list="true"
  :multiple="false"
  :file-list="voiceFile"
  :on-remove="handleRemove"
  :limit="1"
  :auto-upload="true"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
>
  <el-button slot="trigger" >选取文件</el-button>
  <div slot="tip">
    只能上传mp3文件,且不超过2M,播放长度不超过60s
  </div>
</el-upload>

文件类型进行判断/限制上传文件大小

beforeAvatarUpload(file) {
  // 文件类型进行判断
  const isAudio = file.type === 'audio/mp3' || file.type === 'audio/mpeg'
  // 限制上传文件大小 2M
  const isLt2M = file.size / 1024 / 1024 < 2
  const isTime60S = this.audioDuration <= 60 ? true : ''
  // 获取时长
  this.getTimes(file)
  if (!isAudio) {
    this.$message.error('上传文件只能是Mp3格式!')
    this.voiceFile = []
  } else if (!isLt2M) {
    this.$message.error('上传文件大小不能超过 2MB!')
    this.voiceFile = []
  } else if (!isTime60S) {
    this.$message.error('上传文件时长不能超过60秒!')
    this.voiceFile = []
  }
  this.loadingBtn = true
  return isAudio && isLt2M && isTime60S
},

获取录音时长

getTimes(file) {
  let content = file
  
  let url = URL.createObjectURL(content)
  let audioElement = new Audio(url)
  audioElement.addEventListener('loadedmetadata', (_event) => {
    this.audioDuration = parseInt(audioElement.duration)
  })
},