- 最终效果
此处已经通过npm安装wavesurfer
- 大致流程:
- 通过接口获取网络资源路径
- 传入该组件(也可以直接当前组件用)
- 初始化wavesurfer音频组件
- 通过fetch下载音频资源,Blob
- 下载完成后,通过
URL.createObjectURL(blob)
转为路径 - 通过
wavesurfer.load(objectURL)
,初始化音频
<template>
<div class="page">
<div class="top">
<div>
<i class="el-icon-view text1" style="color: #736d6d" />
<span class="text2">浏览量: </span>
<span class="text3">{{ formdata.views }}</span>
</div>
</div>
<div class="main">
<div class="main-box">
<!-- 音频插件 -->
<div class="waveform" ref="wavesurfer"></div>
</div>
<div class="main-button">
<el-button @click="start()">播放</el-button>
<el-button @click="end()">暂停</el-button>
</div>
</div>
<video v-show="false" ref="Video" class="self_video" />
</div>
</template>
<script>
import WaveSurfer from 'wavesurfer.js'
export default {
props: {
// 音频路径通过父级组件传递至此(父级组件是通过接口获取的路径)
formdata: {
type: Object,
default: () => {}
}
},
data() {
return {
wavesurfer: null
}
},
mounted() {
this.init()
},
methods: {
// 初始化
init() {
const wavesurfer = WaveSurfer.create({
// 元素及样式
container: this.$refs.wavesurfer,
height: 340,
progressColor: '#e03639',
waveColor: '#e7e7e7',
cursorColor: '#FFDDDD',
// 波峰宽度
barWidth: 8,
// 是否启用媒体自带的audio控件
mediaControls: false,
// 跨域配置
backend: 'MediaElement',
xhr: {
mode: 'no-cors'
}
})
// 拼接当前项目的路径
const url = process.env.VUE_APP_HOME + this.formdata.fileUri
fetch(url, {
method: 'get',
responseType: 'blob'
})
.then(res => {
return res.blob()
})
.then(blob => {
// 将文件保存下来,并获取路径
const objectURL = URL.createObjectURL(blob)
// 通过保存的路径进行访问
wavesurfer.load(objectURL)
})
this.wavesurfer = wavesurfer
},
// 播放
start() {
this.wavesurfer.play()
},
// 暂停
end() {
this.wavesurfer.pause()
}
}
}
</script>
- 注意事项:
- 后端需要配置跨域!后端需要配置跨域!后端需要配置跨域!
- 我通过在F12的控制台,用
fetch
直接打开资源路径,是没有问题的