js-audio-recorder录音播放波形图

js-audio-recorder录音播放波形图

安装:

npm i js-audio-recorder

调用:

import Recorder from 'js-audio-recorder';
let recorder = new Recorder();

首先,要用到两个canvas标签

<canvas id="recordCanvas" ref="record"></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();
        },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值