vue解決音頻可視化播放,使用wavesurfer.js
上效果:
1.安裝wavesurfer
?npm install wavesurfer.js
2.在頁面導(dǎo)入
import WaveSurfer from 'wavesurfer.js'
注:我沒有使用時(shí)間軸万牺,所以沒有引入叭披,如果需要再引入
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",
????????//使用時(shí)間軸插件
??????});
??????//?特別提醒:此處需要使用require(相對(duì)路徑),否則會(huì)報(bào)錯(cuò)
??????this.wavesurfer.load(require("../mp3/living.mp3"));
????});
??},
??methods:?{
????playMusic()?{
??????//"播放/暫停"按鈕的單擊觸發(fā)事件鹏往,暫停的話單擊則播放议双,正在播放的話單擊則暫停播放
??????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.注釋:
這個(gè)插件實(shí)在太吊了,官方文檔太厲害汛闸,上鏈接:https://wavesurfer-js.org/
我用到了幾個(gè)方法:
4.1.this.wavesurfer.play(0, 212); 指定開始時(shí)間和結(jié)束時(shí)間蝙茶,以秒為單位,0秒開始诸老,212秒結(jié)束
4.2.this.wavesurfer.on("pause", () => {
? ? ? ? ? ? ? console.log('我暫停了')
? ? ? ? ? ? });
監(jiān)聽暫停
4.3.this.wavesurfer.load(require("../mp3/living.mp3")); 讀取目錄路徑里面的Mp3文件隆夯,可以測(cè)試用
this.wavesurfer.load('xxx.mp3')); 讀取網(wǎng)絡(luò)地址,有接口就用這個(gè)