wavesurfer.js的信息
https://github.com/katspaugh/wavesurfer.js
https://wavesurfer-js.org/docs/events.html
安装
yarn add wavesurfer.js
使用
<div class="voice-dialog-content">
<div>
<Button :type="!isPlaying ? 'primary' : 'warning'" shape="circle" :icon="!isPlaying ? 'ios-play' : 'ios-pause'" @click="playVoice"></Button>
</div>
<div id="waveform" ref="waveform"/>
<div class="voice-dialog-time">
<p>{{ time }}</p>
</div>
</div>
import WaveSurfer from 'wavesurfer.js'
import CursorPlugin from 'wavesurfer.js/dist/plugin/wavesurfer.cursor.js'
export default{
props: {
rebot:{
type: Object
},
person:{
type:Object
},
url:{
type: String,
default: require("../../../assets/image/test.mp3")
},
toStopVoice:{
type: Boolean,
default: false
},
loadWave:{
type: Boolean,
default: true
}
},
data(){
return{
wavesurfer: null,
time: '00:00',
isPlaying: false
}
},
mounted() {
this.$nextTick(() => {
if (this.loadWave) {
this.loadVoice()
}
})
},
methods:{
buZero(num) {
return num > 9 ? num : '0' + num
},
loadVoice(bool) {
if (this.wavesurfer) {
if (bool) {
this.time = '00:00'
this.wavesurfer.load(this.url)
}
} else {
this.wavesurfer = WaveSurfer.create({
container: this.$refs.waveform,
waveColor: '#65da74',
progressColor: 'purple',
height: '80',
backgroundColor:"#f7f3f4",
scrollParent: true,
plugins: [
CursorPlugin.create({
showTime: true,
opacity: 1,
customShowTimeStyle: {
'background-color': '#000',
color: '#fff',
padding: '2px',
'font-size': '10px'
}
})
]
})
this.wavesurfer.load(this.url)
this.wavesurfer.on('audioprocess', (e) => {
const times = Math.ceil(e)
this.time = this.buZero(Math.floor(times / 60)) + ':' + this.buZero(times % 60)
})
this.wavesurfer.on('finish', () => {
this.isPlaying = false
})
}
},
playVoice() {
if (this.wavesurfer) {
if (this.wavesurfer.isPlaying()) {
this.isPlaying = false
this.wavesurfer.pause()
} else {
this.isPlaying = true
this.wavesurfer.play()
}
}
}
},
watch: {
'loadWave': function() {
this.playVoice()
},
'url': function() {
this.playVoice(true)
},
'toStopVoice': function() {
if (this.wavesurfer) {
this.wavesurfer.pause()
}
}
},
}
.voice-dialog-content{
display: flex;
align-items: center;
}
#waveform{
margin-left: 4px;
margin-bottom: 4px;
width: 98%;
}
.voice-dialog-time{
margin-left: 3px;
}
- 运行效果
