首页 > 其他分享 >Vue input上传音频并播放

Vue input上传音频并播放

时间:2023-03-09 17:46:30浏览次数:41  
标签:Vue audioContext audioSource 音频 播放 input null audioFile

<template>
  <div>
    <input type="file" ref="audioInput" @change="handleFileUpload">
    <button @click="handleFileSelect">选择音频文件</button>
    <button @click="playAudio">播放音频</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      audioContext: null,
      audioBuffer: null,
      audioSource: null,
      audioFile: null
    }
  },
  methods: {
    handleFileSelect() {
      this.$refs.audioInput.click()
    },
    handleFileUpload(event) {
      // 获取上传的音频文件
      this.audioFile = event.target.files[0]

      // 创建新的音频上下文
      this.audioContext = new AudioContext()

      let reader = new FileReader()
      reader.onload = e => {
        let audioData = e.target.result

        // 解码音频数据
        this.audioContext.decodeAudioData(audioData, buffer => {
          this.audioBuffer = buffer
          this.playAudio()
        }, error => {
          console.error('音频解码错误', error)
        })
      }
      reader.readAsArrayBuffer(this.audioFile)
    },
    playAudio() {
      // 停止正在播放的音频
      if (this.audioSource) {
        this.audioSource.stop()
      }

      // 创建音频源并开始播放
      this.audioSource = this.audioContext.createBufferSource()
      this.audioSource.buffer = this.audioBuffer
      this.audioSource.loop = false
      this.audioSource.connect(this.audioContext.destination)
      this.audioSource.start()
    }
  }
}
</script>

  

标签:Vue,audioContext,audioSource,音频,播放,input,null,audioFile
From: https://www.cnblogs.com/shining-feifan/p/17199353.html

相关文章