需求最终实现的是对话这种,音频+文字的对话
使用方法:
npm install wavesurfer.js --save
官方文档:
https://wavesurfer-js.org/
参数,方法可以去文档查看
直接放封装组件代码
开发背景vue3+ts
WaveSurfer.vue
<template>
<Spin :tip="null" :spinning="loadLoading">
<div :class="`wave-surfer-${index}`" class="flex items-center">
<Icon class="playIcon" :icon="icon" prefix="ali" @click="playMusic" />
</div>
</Spin>
</template>
<script lang="ts">
import { Spin } from 'ant-design-vue';
import { defineComponent, toRefs, ref, onMounted, nextTick, h } from 'vue';
import WaveSurfer from 'wavesurfer.js';
import Icon from '/@/components/Icon';
export default defineComponent({
name: 'WaveSurfer',
components: { Icon, Spin },
props: {
waveSrc: {
type: String,
default: 'http://localhost:3100/src/components/WaveSurfer/src/01.mp3',
},
index: {
type: Number,
},
},
setup(props) {
const { waveSrc, index } = toRefs(props);
const icon = ref('icon-bofang');
let wavesurfer = [];
const loadLoading = ref(false);
function render(id, selector, url) {
loadLoading.value = true;
var domEl = document.createElement('div');
domEl.setAttribute('id', 't-' + id);
domEl.setAttribute('class', 'waveform');
document.querySelector(selector).appendChild(domEl);
let trackid = 't-' + id;
wavesurfer[trackid] = WaveSurfer.create({
container: domEl,
waveColor: '#C2C2C2',
progressColor: '#2273FF',
cursorColor: '#fff',
height: 18,
barWidth: 2,
barGap: 1,
});
wavesurfer[trackid].load(url);
wavesurfer[trackid].on('error', function (e) {
console.warn(e);
});
wavesurfer[trackid].on('ready', function () {
console.log('111111');
loadLoading.value = false;
});
return wavesurfer[trackid];
}
onMounted(() => {
nextTick(() => {
render(index.value, '.wave-surfer-' + index.value, waveSrc.value);
});
});
function playMusic() {
let trackid = 't-' + index.value;
if (icon.value == 'icon-bofang') {
icon.value = 'icon-zanting';
wavesurfer[trackid].play();
} else {
icon.value = 'icon-bofang';
wavesurfer[trackid].playPause();
}
}
return { playMusic, icon, loadLoading };
},
});
</script>
<style lang="less">
.playIcon {
line-height: 18px;
font-size: 18px;
margin-right: 8px;
cursor: pointer;
}
.waveform {
width: calc(100% - 18px);
}
</style>