vue录音+js-audio-recorder

小小记录一下项目中用到的录音功能

1.下载插件

npm i js-audio-recorder

2.展示代码

<template>
  <div style="padding: 20px;">

    <div style="font-size:14px">
      <h3>录音时长:{{ recorder && recorder.duration.toFixed(0) }}s</h3>
      <br />
      <button type="primary" @click="handleStart">开始录音</button>
      <button type="warning" @click="handleStop">停止录音</button>
      <br />
      <br />
      <h3>
        播放时长:{{
          recorder &&
            (playTime > recorder.duration
              ? recorder.duration.toFixed(0)
              : playTime.toFixed(0))
        }}s
      </h3>
      <br />
      <button type="primary" @click="handlePlay">播放录音</button>
      <button type="info" @click="handlePausePlay">暂停播放</button>
      <button type="success" @click="handleResumePlay">继续播放</button>
      <button type="warning" @click="handleStopPlay">停止播放</button>
      <button type="primary" @click="uploadRecord">上传</button>
    </div>
  </div>
</template>

<script>
import Recorder from 'js-audio-recorder'
const parameter = {
        sampleBits: 8, // 采样位数,支持 8 或 16,默认是16
        sampleRate: 11025, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000
        numChannels: 1 // 声道,支持 1 或 2, 默认是1
}
export default {
  data() {
    return {
      recorder: null,
      playTime: 0,
      timer: null,
      src: null,
      setTime:0
    }
  },
  created() {
    this.recorder = new Recorder(parameter)
  },
  methods: {
    // 开始录音
    handleStart() {
      var that = this
      that.recorder = new Recorder()
      Recorder.getPermission().then(() => {
        console.log('开始录音')
        that.recorder.start()// 开始录音
//限制录音时长
        that.setTime= setTimeout(function(){
          that.handleStop()
          alert('录音时间到')
        },180000)
      }, (error) => {
        that.$message({
          message: '请先允许该网页使用麦克风',
          type: 'info'
        })
        console.log(`${error.name} : ${error.message}`)
      })

    },
    handleStop() {
      console.log('停止录音')
    
      this.recorder.stop() // 停止录音
      clearTimeout(this.setTime)
      // this.recorder.duration= 0;
      console.log('时长',this.recorder.duration)
    },
    handlePlay() {
      console.log('播放录音')
      console.log(this.recorder)
      this.recorder.play() // 播放录音

      // 播放时长
      this.timer = setInterval(() => {
        try {
          this.playTime = this.recorder.getPlayTime()
        } catch (error) {
          this.timer = null
        }
      }, 100)
    },
    handlePausePlay() {
      console.log('暂停播放')
      this.recorder.pausePlay() // 暂停播放

      // 播放时长
      this.playTime = this.recorder.getPlayTime()
      this.time = null
    },
    handleResumePlay() {
      console.log('恢复播放')
      this.recorder.resumePlay() // 恢复播放

      // 播放时长
      this.timer = setInterval(() => {
        try {
          this.playTime = this.recorder.getPlayTime()
        } catch (error) {
          this.timer = null
        }
      }, 100)
    },
    handleStopPlay() {
      console.log('停止播放')
      this.recorder.stopPlay() // 停止播放

      // 播放时长
      this.playTime = this.recorder.getPlayTime()
      this.timer = null
    },
    handleDestroy() {
      console.log('销毁实例')
      this.recorder.destroy() // 毁实例
      this.timer = null
    },
    uploadRecord() {
      if (this.recorder == null || this.recorder.duration === 0) {
        console.log('请先录音')
        // this.$message({
        //   message: '请先录音',
        //   type: 'error'
        // })
        return false
      }
      this.recorder.pause() // 暂停录音
      this.timer = null
      console.log('上传录音')// 上传录音


      const formData = new FormData()
      const blob = this.recorder.getWAVBlob()// 获取wav格式音频数据
      // 此处获取到blob对象后需要设置fileName满足当前项目上传需求,其它项目可直接传把blob作为file塞入formData
      const newbolb = new Blob([blob], { type: 'audio/wav' })
      const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
      formData.append('file', fileOfBlob)

      const url = window.URL.createObjectURL(fileOfBlob)//通过blob对象获取到播放url
      this.src = url
      console.log(blob)

      // const axios = require('axios')上传后台
      // axios.post(url, formData).then(res => {
      //   console.log(res.data.data[0].url)
      // })
    }
  }
}
</script>

重点:最后发现停止录音还会占用录音权限

稍作修改(停止录音把录音文件传入blob,关闭录音用到销毁实例会删除这个流让录音的小标志消失)

1.

    // 开始录音
    handleStart() {
      var that = this;
      that.recorder = new Recorder();
      Recorder.getPermission().then(
        () => {
          that.kFlag = false;
          that.dFlag = true;
          console.log("开始录音");
          that.recorder.start(); // 开始录音
          clearTimeout(this.setTime);
          that.setTime = setTimeout(function () {
            that.stopRecord();
            alert("录音时间到");
          }, 180000);
        },
        (error) => {
          that.$message({
            message: "请先允许该网页使用麦克风",
            type: "info",
          });
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },

2.

    stopRecord() {
      if (this.recorder == null || this.recorder.duration === 0) {
        Dialog({
          message: `<div style="font-size:18px;">请先录音</div>`,
          width: 200,
          height: 50,
        });
        return false;
      }
      console.log("停止录音");
      this.kFlag = true;
      this.dFlag = false;
      this.recorder.stop(); // 停止录音
      // this.drawRecordId && cancelAnimationFrame(this.drawRecordId);
      //   this.drawRecordId = null;
      clearTimeout(this.setTime);

      const formData = new FormData();
      this.blob = this.recorder.getWAVBlob(); // 获取wav格式音频数据
      // 此处获取到blob对象后需要设置fileName满足当前项目上传需求,其它项目可直接传把blob作为file塞入formData
      const newbolb = new Blob([this.blob], { type: "audio/wav" });
      const fileOfBlob = new File([newbolb], new Date().getTime() + ".wav");
      formData.append("file", fileOfBlob);

      const url = window.URL.createObjectURL(fileOfBlob); //通过blob对象获取到播放url
      this.src = url;
      console.log(this.blob);
    },

3.

    handleStop() {
      console.log("关闭录音");
      this.recorder.destroy(); // 毁实例
      console.log(this.blob);
    },

成果 

 

 

 

 

 

 需要其他效果可以通过

 3.插件地址Introduction · recorder

自行添加

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值