Vue项目使用js-audio-recorder录音及录音文件上传

阎佑运
2023-12-01

最近在做的Vue项目里有关于录音和录音文件上传的功能,用到的是一个开源框架js-audio-recorder,官方文档上关于录音、暂停录音等也封装了很多方法,在这里我主要说下录音文件上传部分,网上找了很多但是关于转换成mp3格式的文件上传的不是太多,在此记录一下也方便后期自己的学习。

目录

Vue项目js-audio-recorder导入和引用

录音

录音文件转mp3格式并上传


Vue项目js-audio-recorder导入和引用

1.使用命令行安装库 

npm i js-audio-recorder

2.项目导入

import Recorder from 'js-audio-recorder';

let recorder = new Recorder();
API的使用方法start()、pause()等官方文档描述的很清楚,这里就不在贴出来了,官方文档:js-audio-plugin

录音

开始录音

let _this = this
      recorder.start().then(() => {
        // 开始录音
        recorder.onprogress = function(params) {
          _this.duration = params.duration.toFixed(2)
          console.log('dur--', this.duration)
          console.log('录音时长(秒)', params.duration.toFixed(2));
          let dataArray = recorder.getRecordAnalyseData();
//          console.log('dataArray--', dataArray)
        }
      }, (error) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      })

录音文件转mp3格式并上传

  • 转为mp3格式需要用到lamejs,安装方法:npm install lamejs   使用:
    import lamejs from 'lamejs'
onEndVoice() {    //结束录音方法调用
  recorder.stop()

  let instance = axios.create({
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  let contentType = "application/json";
  let mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
  let formData = new FormData()
  let  file = this.convertToMp3(recorder.getWAV())
  file = new File([file],mp3Name)
  formData.append("file",file)
  formData.append("mp3Name",mp3Name)
  instance.post('http://172.17.xx.xxx:8080/visit/uploadFile', formData).then(res => {
    console.log('res---', res)
  })
},
convertToMp3(wavDataView) {
  // 获取wav头信息
  const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息,毕竟有对应的config配置
  const { channels, sampleRate } = wav;
  console.log('wav', wav)
  const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
  // 获取左右通道数据
  const result = recorder.getChannelData()
  const buffer = [];

  const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
  const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
  const remaining = leftData.length + (rightData ? rightData.length : 0);

  const maxSamples = 1152;
  for (let i = 0; i < remaining; i += maxSamples) {
    const left = leftData.subarray(i, i + maxSamples);
    let right = null;
    let mp3buf = null;

    if (channels === 2) {
      right = rightData.subarray(i, i + maxSamples);
      mp3buf = mp3enc.encodeBuffer(left, right);
    } else {
      mp3buf = mp3enc.encodeBuffer(left);
    }

    if (mp3buf.length > 0) {
      buffer.push(mp3buf);
    }
  }

  const enc = mp3enc.flush();

  if (enc.length > 0) {
    buffer.push(enc);
  }

  return new Blob(buffer, { type: 'audio/mp3' });
},

 

 类似资料: