js-audio-recorder录音播放波形图
安装:
npm i js-audio-recorder
调用:
import Recorder from 'js-audio-recorder'; let recorder = new Recorder();
基本功能看官网:https://recorder-api.zhuyuntao.cn/
播放时的波形图,一开始没搞出来,后面看了人家的例子,才弄好,这里记录一下:
首先,要用到两个canvas标签
<canvas id="recordCanvas" ref="record"></canvas> <canvas id="playCanvas" ref="play"></canvas>
data() {
return {
recorder: null, // 录音
drawRecordId: null,
drawPlayId: null,
}
},
mounted(){
this.recorder = new Recorder()
},
其次,录音波形和播放波形,要用不同的方法获取,getRecordAnalyseData() 和 getPlayAnalyseData()
// 开始录音 handleStart() { this.recorder = new Recorder() Recorder.getPermission().then(() => {this.recorder.start().then(() => { this.drawRecord(); }) }, (error) => { console.log(`${error.name} : ${error.message}`) }) }, // 停止录音 handleStop() {this.recorder.stop() this.drawRecordId && cancelAnimationFrame(this.drawRecordId); this.drawRecordId = null; }, // 播放录音 handlePlay() {this.recorder.play() this.drawPlay(); },
最后,录音完了,要将 drawRecordId 和 drawPlayId 销毁
// 录音波浪图 drawRecord(){ // 用requestAnimationFrame稳定60fps绘制 this.drawRecordId = requestAnimationFrame(this.drawRecord) this.drawWave({ canvas: this.$refs.record, dataArray: this.recorder.getRecordAnalyseData(), }); }, // 播放波浪图 drawPlay(){ // 用requestAnimationFrame稳定60fps绘制 this.drawPlayId = requestAnimationFrame(this.drawPlay); this.drawWave({ canvas: this.$refs.play, dataArray: this.recorder.getPlayAnalyseData(), }); }, // 绘制波形图 drawWave({canvas, dataArray}) { const ctx = canvas.getContext("2d"); const bufferLength = dataArray.length; // 填充背景色 ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); // 设定波形绘制颜色 ctx.lineWidth = 2; ctx.strokeStyle = "#409EFF"; ctx.beginPath(); var sliceWidth = (canvas.width * 1.0) / bufferLength, // 一个点占多少位置,共有bufferLength个点要绘制 x = 0; // 绘制点的x轴位置 for (var i = 0; i < bufferLength; i++) { var v = dataArray[i] / 128.0; var y = (v * canvas.height) / 2; if (i === 0) { // 第一个点 ctx.moveTo(x, y); } else { // 剩余的点 ctx.lineTo(x, y); } // 依次平移,绘制所有点 x += sliceWidth; } ctx.lineTo(canvas.width, canvas.height / 2); ctx.stroke(); },