奧學家特別招募計劃啟動!申請入隊即可抽取迪迦手辦!
vue解決音訊視覺化播放,使用wavesurfer.js
上效果:
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;
#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')); 讀取網路地址,有介面就用這個