基于vue2 给录音文件添加比特率和其他配置

56 阅读1分钟
背景: 在开发中,通过浏览器录音发现拿到的文件没有比特率,导致服务端无法解析语音的文字,所以四处寻找,找到了这个插件,经过调整,发现能满足开发需求,音频也可以灵活配置比特率,使音频更清晰了

1.安装 js-audio

  npm i js-audio-recorder //"js-audio-recorder": "^1.0.7" 目前我是用的1.0.7

2.新建组件MP3

 <template>
    <div>
    <div class="AudioRecorder2"></div>
        <button @click="startRecordAudio">开始录音</button>
        <button @click="stopRecordAudio">终止录音</button>
        <button @click="playRecordAudio">playRecordAudio</button> 
        <audio  ref="audioPlayer" controls></audio> 
    </div>
  </template> 
<script>
  
import {  audio_fileFun } from '@/api/TrendAnalysis';
  import Recorder from 'js-audio-recorder'    
  export default {
    name: 'AudioRecorder2',
    components: {},
    data() {
      return {
        recorder: new Recorder({
          sampleBits: 16, // 采样位数,支持 8 或 16,默认是16
          sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000
          numChannels: 1, // 声道,支持 1 或 2, 默认是1
          // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换,默认是false
          playTimer: null,
          isrecording: false, // 当前是否在录音
          isDestory: false // 是否销毁
        })
      }
    },  
    mounted() {
      this.$nextTick(() => {
        this.startRecordAudio()
      })
    },
    beforeDestroy() {
      this.isDestory = true // 准备销毁
      this.stopRecordAudio()
    },
    destroyed() {
      console.log('录音实例销毁-----------')
      // 销毁录音实例,置为null释放资源,fn为回调函数,
      this.recorder.destroy().then(() => {
        this.recorder = null
      })
    },
    methods: {
      // 开始录音
      startRecordAudio() {
        if (this.isDestory) {
          return
        }
        Recorder.getPermission().then(
          (res) => {
            console.log('开始录音=============', res)
            this.recorder.start() // 开始录音
            this.isrecording = true // 录制中
            setTimeout(() => {
              this.stopRecordAudio()
            }, 1000 * 60 * 10)
          },
          error => {
            console.log('======请先允许该网页使用麦克风')
            console.log(`${error.name} : ${error.message}`)
          }
        )
      },
      // 停止录音
      stopRecordAudio() {
        if (this.isrecording) {
          console.log('停止录音-----------------')
          this.isrecording = false
          this.recorder.stop()
          this.uploadWAVData()
        } else {
          console.log('没有需要停止的录音------------')
        }
      },
      // 播放录音
      playRecordAudio() {
        console.log('播放录音')
        this.recorder.play()
      },
      // 上传wav录音数据获取文件id
      uploadWAVData() { 
        const fileName = '一把过啊兄弟-20221214172357.mp3 '
        const wavBlob = this.recorder.getWAVBlob()
        // 创建一个formData对象
        const formData = new FormData()
        const newbolb = new Blob([wavBlob], { type: 'audio/mp3' })

    //  const blob = new Blob(this.chunks, { type: 'audio/mpeg' });
    // const formData = new FormData();
    // formData.append('audio_file', blob, 'recording.mp3');
     
        // 获取当时时间戳作为文件名
        const fileOfBlob = new File([newbolb], fileName)

        formData.append('audio_file', newbolb) 
        this.$refs.audioPlayer.src = fileOfBlob
        
        //传递给后端的 bolb 对象
        audio_fileFun(formData).then((res) => {
            console.log(res)
        });
      },
      // 保存录音文件
      handleSaveFile(id) {
        const params = {
          fileIds: [id],
          subjectIcfRecordId: this.subjectIcfRecordId
        }
      }
    }
  }
  </script>
  
  <style></style>

3.引入组件

 <mp3 />