2021/9/24 js-audio-recorder实现录音功能

开始录音

// 开始录音

    startRecorder() {
      let that = this;
      recorder.start().then(
        () => {
          this.disnext = true;
          // 绑定事件-打印的是当前录音数据
          recorder.onprogress = function (params) {
            that.duration = params.duration.toFixed(3);
          };

          // this.duration = recorder.duration;
          this.drawRecord(); //绘制波浪图
          setTimeout(function () {
            document.getElementById("instructions").style.backgroundColor =
              "green";
          }, 300); //三秒之后变色
        },
        (error) => {
          // 出错了

          console.log(`${error.name} : ${error.message}`);
        }
      );
    },

结束录音

 // 结束录音

    stopRecorder() {
      this.disnext = false;
      this.duration = recorder.duration.toFixed(3);
      setTimeout(function () {
        document.getElementById("instructions").style.backgroundColor = "red";
      }, 300); //三秒之后变色
      console.log(recorder.getWAVBlob(), "结束录音");
      //获取 WAV 数据,在录音结束后使用 -使用该方法会默认调用 stop() 方法。
      const Blob = recorder.getWAVBlob();
      //创建一个新的 URL 对象
      this.url = URL.createObjectURL(Blob);
      // console.log(this.url, "地址");
      // recorder.downloadWAV();
    },

实现波形图

//  波浪图配置
    startCanvas() {
      //录音波浪
      this.oCanvas = document.getElementById("canvas");
      this.ctx = this.oCanvas.getContext("2d");
    },
// 录音  音波图
    drawRecord() {
      // 用requestAnimationFrame稳定60fps绘制
      this.drawRecordId = requestAnimationFrame(this.drawRecord);

      // 实时获取音频大小数据
      let dataArray = recorder.getRecordAnalyseData(),
        bufferLength = dataArray.length;

      // 填充背景色
      this.ctx.fillStyle = "#fff";
      this.ctx.fillRect(0, 0, this.oCanvas.width, this.oCanvas.height);

      // 设定波形绘制颜色
      this.ctx.lineWidth = 2;
      this.ctx.strokeStyle = "#409EFF";

      this.ctx.beginPath();

      var sliceWidth = (this.oCanvas.width * 1.0) / bufferLength, // 一个点占多少位置,共有bufferLength个点要绘制
        x = 0; // 绘制点的x轴位置

      for (var i = 0; i < bufferLength; i++) {
        var v = dataArray[i] / 128.0;
        var y = (v * this.oCanvas.height) / 2;

        if (i === 0) {
          // 第一个点
          this.ctx.moveTo(x, y);
        } else {
          // 剩余的点
          this.ctx.lineTo(x, y);
        }
        // 依次平移,绘制所有点
        x += sliceWidth;
      }

      this.ctx.lineTo(this.oCanvas.width, this.oCanvas.height / 2);
      this.ctx.stroke();
    },

wavesurfer.js

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值