audio效果
使用wavesurfer.js做成可视化音波音频
首先要先下载好wavesurfer.js依赖
npm install wavesurfer.js --save
或者
yarn add wavesurfer.js
下载完之后,考虑到直接使用在现有的页面上,会显得代码很多,而且无法复用,这里直接做成一个工具类,给大家参考使用
<template>
<div v-if="audioUrl && audioUrl !== ''" style="width: 100%">
<a-spin :spinning="loading"></a-spin>
<div ref="waveform"></div>
<div ref="timeline"></div>
<input type="range" v-model="currentTime" :max="duration" @input="seek" style="width: 100%">
<button @click="playPause">{{ isPlaying ? '暂停' : '播放' }}</button>
</div>
</template>
<script>
import WaveSurfer from 'wavesurfer.js';
import TimelinePlugin from 'wavesurfer.js/dist/plugins/timeline.esm.js';
export default {
name: 'WaveSurferTool',
props: {
audioUrl: {
type: String,
required: true
},
waveColor: {
type: String,
default: 'violet'
},
progressColor: {
type: String,
default: 'purple'
}
},
data() {
return {
waveSurfer: null,
loading: true,
isPlaying: false,
currentTime: 0,
duration: 0
}
},
mounted() {
let that = this;
this.waveSurfer = WaveSurfer.create({
container: this.$refs.waveform,
waveColor: this.waveColor,
progressColor: this.progressColor,
width: '912px',
plugins: [
TimelinePlugin.create({
container: this.$refs.timeline,
height: 20,
timeInterval: 5,
primaryLabelInterval: 5,
secondaryLabelInterval: 1,
style: {
fontSize: '14px', // 调整字体大小
lineHeight: '1.2', // 调整行高
color: '#2D5B88'
}
})
],
url: this.audioUrl
});
this.waveSurfer.on('ready', function () {
console.log('初始化结束');
that.loading = false;
that.duration = that.waveSurfer.getDuration();
});
this.waveSurfer.on('click', () => {
this.playPause();
});
this.waveSurfer.on('audioprocess', () => {
this.currentTime = this.waveSurfer.getCurrentTime();
});
},
beforeDestroy() {
if (this.waveSurfer) {
this.waveSurfer.destroy();
}
},
methods: {
playPause() {
if (this.isPlaying) {
this.waveSurfer.pause();
} else {
this.waveSurfer.play();
}
this.isPlaying = !this.isPlaying;
},
seek() {
this.waveSurfer.seekTo(this.currentTime / this.duration);
}
}
}
</script>
具体使用方法,在需要使用转成可视化的地方直接引用即可,:audioUrl对应的路径,做线上的话就要发送http请求才能拿到录音文件!