前端使用el-upload上传音频后,获取文件流
声明四个要使用的变量
this.audioFile = file.raw//获取上传的音频文件
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 = true
this.audioSource.connect(this.audioContext.destination)
this.audioSource.start()
}