原文链接:https://www.jianshu.com/p/1996c7f105e3
上效果:
未播放时
已经播放时
1.安装wavesurfer
npm install wavesurfer.js
2.在页面导入
import WaveSurfer from 'wavesurfer.js'
注:我没有使用时间轴,所以没有引入,如果需要再引入
import Timeline from 'wavesurfer.js/dist/plugin/wavesurfer.timeline.js'
3.上源码
<template> <el-row> <el-card class="card" :body-style="{ padding: '10px' }"> <div id="waveform" ref="waveform"> </div> </el-card> </el-row> <div> <el-button type="primary" @click="playMusic"> <i class="el-icon-video-play"></i> 播放 / <i class="el-icon-video-pausee"></i> 暂停 </el-button> </div> </template> <script> import WaveSurfer from "wavesurfer.js"; // import Timeline from "wavesurfer.js/dist/plugin/wavesurfer.timeline.js"; export default { name: "Details", data() { return { wavesurfer: null, }; }, mounted() { this.$nextTick(() => { this.wavesurfer = WaveSurfer.create({ container: this.$refs.waveform, // waveColor: '#409EFF', barWidth: 1, cursorColor: "black", progressColor: "blue", backend: "MediaElement", // mediaControls: false, audioRate: "1", //使用时间轴插件 }); // 特别提醒:此处需要使用require(相对路径),否则会报错 this.wavesurfer.load(require("../mp3/living.mp3")); }); }, methods: { playMusic() { //"播放/暂停"按钮的单击触发事件,暂停的话单击则播放,正在播放的话单击则暂停播放 this.wavesurfer.playPause.bind(this.wavesurfer)(); }, }, }; </script> <style > .mixin-components-container { width: 100% !important; background-color: #f0f2f5; padding: 30px; /* min-height: calc(100vh - 84px); */ } .el-card__body { width: 100% !important; height: 70px !important; padding: 0 auto !important; } .card { width: 100% !important; height: 70px; } #waveform { height: 70px !important; } wave { height: 50px !important; } </style>
4.注释:
这个插件实在太吊了,官方文档太厉害,上链接:https://wavesurfer-js.org/
我用到了几个方法:
4.1.this.wavesurfer.play(0, 212); 指定开始时间和结束时间,以秒为单位,0秒开始,212秒结束
4.2.this.wavesurfer.on("pause", () => {
console.log('我暂停了')
});
监听暂停
4.3.this.wavesurfer.load(require("../mp3/living.mp3")); 读取目录路径里面的Mp3文件,可以测试用
this.wavesurfer.load('xxx.mp3')); 读取网络地址,有接口就用这个