最近公司有个需求,在屏幕上使用麦克风进行语音录制,还要根据声音大小生成音频波形图,身为小菜鸡的我,在网上搜了好久,没有找到满意的文档,最后一个大佬说了这个wavesurfer.js,然后去查了下资料,其实查资料的时候,Wavesurfer.js这种录音的也是很少,怕达不到公司的需求,将着半信半疑的心态,写了个demo,费了些许时间,因为总会有这种那种问题,网上的文章总跟实际用的时候有些出入
官方文档:wavesurfer.xyz/docs/
demo效果图:
首先了解下什么是wavesurfer.js
wavesurfer.js是基于Web Audio API 和HTML5 Canvas实现的一个可定制化的音频波形可视化组件,在需要音频波形展示及音频波形交互的场景有广泛的应用
通过官方文档发现,wavesurfer.js中有一些配置项和插件,可以达到想要的效果,既然这个需求是录音,那就用Record插件:wavesurfer.xyz/docs/module…
使用wavesurfer.js必须在https下进行使用,不然浏览器不会申请麦克风权限
安装wavesurfer.js,安装的时候,wavesurfer.js版本默认的:7.8.4
npm i wavesurfer.js
在使用的页面引入wavesurfer.js和Record插件
import WaveSurfer from 'wavesurfer.js';
import RecordPlugin from 'wavesurfer.js/dist/plugins/record.esm';
创建wavesurfer.js实例,初始化一些基础的配置项,可以看文档wavesurfer.xyz/docs/types/…
this.wavesurfer = WaveSurfer.create({
container: this.$refs.waveform,
waveColor: '#FCB28F', // 设置波形颜色
progressColor: '#FCB28F', // 设置进度条颜色
height: 150, // 设置波形图高度
barWidth: 10, // 设置条形宽度
barRadius: 2, // 设置条形圆角
cursorWidth: 0, // 设置光标宽度
});
设置录音的选项,
this.record = this.wavesurfer.registerPlugin(
RecordPlugin.create({
scrollingWaveform: false,
})
);
this.record.on('record-end', (blob) => {
this.recordedUrl = URL.createObjectURL(blob);
this.recordedBlobType = blob.type.split(';')[0].split('/')[1] || 'webm';
});
this.record.on('record-progress', (time) => {
console.log('更新进度条', time);
});
开始录音
startRecording() {
this.record.startRecording().then(() => {
console.log('开始录音');
});
},
结束录音
stopRecording() {
this.record.stopRecording();
},
完整代码
<template>
<div>
<div ref="waveform"></div>
<button @click="startRecording">Start Recording</button>
<button @click="stopRecording">Stop Recording</button>
</div>
</template>
<script>
import WaveSurfer from 'wavesurfer.js';
import RecordPlugin from 'wavesurfer.js/dist/plugins/record.esm';
export default {
data() {
return {
wavesurfer: null,
record: null,
recordedUrl: '',
recordedBlobType: '',
};
},
mounted() {
this.init();
},
beforeDestroy() {
if (this.wavesurfer) {
this.wavesurfer.destroy();
}
},
methods: {
async init() {
this.wavesurfer = WaveSurfer.create({
container: this.$refs.waveform,
waveColor: '#FCB28F', // 设置波形颜色
progressColor: '#FCB28F', // 设置进度条颜色
height: 150, // 设置波形图高度
barWidth: 10, // 设置条形宽度
barRadius: 2, // 设置条形圆角
cursorWidth: 0, // 设置光标宽度
});
this.record = this.wavesurfer.registerPlugin(
RecordPlugin.create({
scrollingWaveform: false,
})
);
this.record.on('record-end', (blob) => {
this.recordedUrl = URL.createObjectURL(blob);
this.recordedBlobType = blob.type.split(';')[0].split('/')[1] || 'webm';
});
this.record.on('record-progress', (time) => {
console.log('更新进度条', time);
});
},
startRecording() {
this.record.startRecording().then(() => {
console.log('开始录音');
});
},
stopRecording() {
this.record.stopRecording();
},
},
};
</script>
<style>
.waveform {
width: 100%;
height: 128px;
}
</style>