vue+pc端录音+canvas音频可视化+输出blob文件+播放录音

本文介绍如何在Vue项目中实现PC端录音功能,并结合Canvas进行音频可视化展示,最后将录音输出为Blob文件并支持播放。通过引入封装好的record.js,实现了在Vue组件中点击触发录音和停止,同时在Canvas上实时展示音频波形。
摘要由CSDN通过智能技术生成
  1. 引入封装好的record.js文件,代码如下
    /* 录音 vue文件 标准版,canvas可视化版 */

    window.URL = window.URL || window.webkitURL
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia
    let HZRecorder = function (stream, config) {
      // const that = this;
      config = config || {}
      config.sampleBits = config.sampleBits || 8 // 采样数位 8, 16
      config.sampleRate = config.sampleRate || (44100 / 6) // 采样率(1/6 44100)
      let context = new(window.webkitAudioContext || window.AudioContext)()
      let audioInput = context.createMediaStreamSource(stream)
      let createScript = context.createScriptProcessor || context.createJavaScriptNode
      let recorder = createScript.apply(context, [4096, 1, 1])
      let transcount = 0;
      let pos = 0;
      let buffer48 = new Float32Array(1024 * 3);
      let buffer16 = new Float32Array(buffer48.length / 3);
      let audioData = {
        size: 0, // 录音文件长度
        buffer: [], // 录音缓存
        inputSampleRate: context.sampleRate, // 输入采样率
        inputSampleBits: 16, // 输入采样数位 8, 16
        outputSampleRate: config.sampleRate, // 输出采样率
        oututSampleBits: config.sampleBits, // 输出采样数位 8, 16
        input: function (data) {
          this.buffer.push(new Float32Array(data))
          this.size += data.length
        },
        compress: function () { // 合并压缩
          // 合并
          let data = new Float32Array(this.size)
          let offset = 0
          for (let i = 0; i < this.buffer.length; i++) {
            data.set(this.buffer[i], offset)
            offset += this.buffer[i].length
          }
          // 压缩
          let compression = parseInt(this.inputSampleRate / this.outputSampleRate)
          let length = data.length / compression
          let result = new Float32Array(length)
          let index = 0;
          let j = 0
          while (index < length) {
            result[index] = data[j]
            j += compression
            index++
          }
          return result
        },
        encodeWAV: function () {
          let sampleRate = Math.min(this.inputSampleRate, this.outputSampleRate)
          let sampleBits = Math.min(this.inputSampleBits, this.oututSampleBits)
          let bytes = this.compress()
          let dataLength = bytes.length * (sampleBits / 8)
          let buffer = new ArrayBuffer(44 + dataLength)
          let data = new DataView(buffer)
          let channelCount = 1 // 单声道
          let offset = 0
 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值