最近有一个在线音波方法的功能需求,考虑使用Wavesurfer.js来实现这块
1.首先安装Wavesurfer.js
npm install wavesurfer.js
2.创建 Wavesurfer 组件
在 Vue 2项目中创建一个音频播放器组件(如 WaveSurferPlayer.vue
),。
<template><div style="padding: 30px"><div ref="waveform_Ref" style="cursor: pointer"></div><!-- 时间信息 --><div class="time-info"><span>当前时间:<span style="color: #72df90">{{ formatTime(currentTime) }}</span></span><span>总时长: {{ formatTime(duration) }}</span></div><div style="padding: 30px; width: 120px; margin: auto"><el-buttontype="success"icon="el-icon-video-play"@click="playMusic"circlev-if="!playing"></el-button><el-buttonv-if="playing"type="danger"icon="el-icon-video-pause"circle@click="playMusic"></el-button></div></div>
</template><script>
import WaveSurfer from "wavesurfer.js";export default {name: "WaveSurferPlayer",props: {audioSrc: {type: String,required: true,},},data() {return {wavesurfer: null,playing: false,duration: 0,currentTime: 0, // 当前播放时间};},mounted() {this.$nextTick(() => {this.wavesurfer = WaveSurfer.create({// 波形图的容器container: this.$refs.waveform_Ref,// 已播放波形的颜色progressColor: "#13ce66",// 未播放波形的颜色// waveColor: "lightgrey",// 波形图的高度,单位为px// height: 10,// 是否显示滚动条,默认为falsescrollParent: true,// 波形的振幅(高度),默认为1// barHeight: 0.8,// 波形条的圆角// barRadius: 2,// 波形条的宽度// barWidth: 1,// 波形条间的间距// barGap: 3// 播放进度光标条的颜色cursorColor: "red",// 播放进度光标条的宽度,默认为1// cursorWidth: 10,// 播放进度颜色// progressColor: "blue",// 波形容器的背景颜色// backgroundColor: "yellow",// 音频的播放速度// audioRate: "1",// (与区域插件一起使用)启用所选区域的循环// loopSelection:false});this.wavesurfer.on("error", (error) => {console.error("音频加载失败:", error);this.$message({type: "error",message: "音频加载失败,请检查文件路径或网络连接",});});this.wavesurfer.load(this.audioSrc);// 监听结束事件this.wavesurfer.on("finish", () => {this.playing = false;});// 监听时间更新事件this.wavesurfer.on("audioprocess", (time) => {this.currentTime = time;});// 监听暂停事件this.wavesurfer.on("pause", () => {this.playing = false;});// 监听音频加载完成事件this.wavesurfer.on("ready", () => {this.duration = this.wavesurfer.getDuration();});});},methods: {// 格式化时间(秒 -> 分:秒)formatTime(time) {const minutes = Math.floor(time / 60);const seconds = Math.floor(time % 60);return `${minutes}:${seconds.toString().padStart(2, "0")}`;},playMusic() {this.wavesurfer.playPause.bind(this.wavesurfer)();this.playing = !this.playing;},},beforeDestroy() {// 销毁 Wavesurfer 实例if (this.wavesurfer) {this.wavesurfer.destroy();}},
};
</script>
<style scoped>
.time-info {font-size: 18px;color: #666;
}
</style>
3.在页面中引入组件,audioUrl是音频路径,把音频文件路径audioUrl子组件传参进去
<WaveSurferPlayer :audioSrc="audioUrl" />
4.页面中显示样式,其中波纹颜色,大小等等都可通过配置项设置