vue使用waveurfer.js

1,695 阅读1分钟

前段时间遇到需要前端生成音频波形图的需求,于是一番查找看到了这个waveurfer插件,满足需求绰绰有余,特此简单记录一下日后方便。

waveurfer.js是可自定义的音频波形可视化,建立在Web Audio API和HTML5 Canvas之上。

更多参数、方法请查询--- 官网

安装waveurfer.js

npm install wavesurfer --save

在需要使用的页面import导入wavesurfer.js;

import WaveSurfer from './../node_modules/wavesurfer/dist/wavesurfer';

在页面中创建容器

<template>
  <div>
       <!-- 音频容器 -->
       <div id="waveform" ref="waveform" />
  </div>
</template>

创建一个实例

  data () {
	return {
	    wavesurfer: null
	}
    },
  methods: {
    getData(){
	let dataList = [{'id':'1','musicUrl':'../123123a.mp3','track':[0.0029, -0.009, 0.0109, -0.0124, 0.0271]}];//模拟数据
	this.wavesurfer = WaveSurfer.create({
	    container: this.$refs.waveform, 
	    //container: '#waveform',//或者这样
	    barWidth: 3,
	    progressColor: "#ddd",
	    backend: 'MediaElement',
	    waveColor: "#666",
	    barGap: 3,
	    height: 80,
	    width:400
	});
	//this.wavesurfer.load() //进入页面加载音频
	//2个参数 先加载音轨生成波形图,点击加载音频
	this.wavesurfer.load(dataList[0].musicUrl, dataList[0].track);

	//没有音轨时需要生成多条需要先获取容器ID,预加载音频生成波形图
        //wavesurfer中的container参数值需要循环获取容器ID;
        for (let i = 0; i < dataList.length; i++) {
	    this.wavesurfer.load(dataList[i].musicUrl);
        }
    }
}

播放 

this.wavesurfer.play() 

暂停 

this.wavesurfer.pause()

... ...