vue中js-audio-recorder,使用websocket进行音频流传输

从获取浏览器录音开始,就是通过websocket实时发送音频流给后端。在这里插入代码片

 handleStart() {
      const uuid = require("uuid");
      this.sessionId = uuid.v4();
      console.log(this.sessionId);

      this.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
      });
      this.recorder.onprocess = (params) => {
        console.log(params)
     
      const formData = new FormData();
      const blob = this.recorder.getWAVBlob(); // 获取wav格式音频数据
      console.log(blob);
      // 此处获取到blob对象后需要设置fileName满足当前项目上传需求,可直接传把blob作为file塞入formData
      const newbolb = new Blob([blob], { type: "audio/wav" });
      const fileOfBlob = new File([newbolb], new Date().getTime() + ".wav");
      console.log(fileOfBlob);
      formData.append("file", blob);
      console.log(formData);
        this.websocketSend(formData)
      
      }
      console.log(this.recorder)
      Recorder.getPermission().then(
        () => {
          console.log("开始录音");

          this.recorder.start(); // 开始录音
           const formData = new FormData();
          const blob = this.recorder.getWAVBlob(); // 获取wav格式音频数据
          console.log(blob);
      
     
        },
        (error) => {
          this.$message({
            message: "请先允许该网页使用麦克风",
            type: "info",
          });
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },
initWebSocket(){ //初始化weosocket
        const wsuri = this.config.ws_server;
        //连接服务端
        this.websock = new WebSocket(wsuri);
        //指定事件回调
        this.websock.onmessage = this.websocketOnMessage;
        this.websock.onopen = this.websocketOnOpen;
        this.websock.onerror = this.websocketOnError;
        this.websock.onclose = this.websocketClose;
        },
 
        websocketOnOpen(){ //连接建立之后执行send方法发送数据
            let actions = {'type': 100, 'msg': 'requestPermission'}
            this.websocketSend(JSON.stringify(actions));
            //连接后,定时发送,否则不段时间不通信会自动断连(时间长短一般是服务端指定的)
            var that = this;
            setInterval(function () {
                that.websocketSend(JSON.stringify({'type': 0, 'msg': 'ping'}));
            }, 15000);
        },
 
        websocketOnError(){//连接建立失败重连
            this.initWebSocket();
        },
 
        websocketOnMessage(e){ //数据接收
            const redata = JSON.parse(e.data);
            // eslint-disable-next-line
            console.log(redata);
            // eslint-disable-next-line
        },
 
        websocketSend(Data){//数据发送
                this.websock.send(Data);
        },
 
        // eslint-disable-next-line
        websocketClose(e){  //关闭
            // eslint-disable-next-line
            console.log('断开连接',e);
        },


点击开始录音把formData传到后端,初始化websocket,链接服务器,指定事件回调,调用websocketSend发送数据的方法。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要实现将 25s 的 wav 数据截取成 5 段 5s 的 wav 数据,您可以按照以下步骤进行: 1. 使用 js-audio-recorder进行录音并获取到 25s 的 wav 数据。 2. 将 25s 的 wav 数据使用 WaveFile 库进行解码,得到音频的采样率和声道数等信息。 3. 计算每一段需要截取的采样数(每一秒的采样率 x 5),并按照此采样数将 25s 的 wav 数据切分成 5 段。 4. 对每一段数据使用 WaveFile 库进行编码并保存成单独的 wav 文件。 以下是一段示例代码,可以帮助您更好地理解实现过程: ```javascript const recorder = new Recorder({ sampleBits: 16, sampleRate: 16000, numChannels: 1 }); // 开始录音 recorder.start(); // 停止录音并获取录音数据 const buffer = recorder.stopAndGetBuffer(); // 将录音数据解码成 WaveFile 对象 const wav = new WaveFile(); wav.fromScratch(1, 16000, '16', buffer); // 计算每一段需要截取的采样数 const sampleRate = wav.fmt.sampleRate; const samplesPerSlice = sampleRate * 5; const totalSamples = wav.data.samples.length; const numSlices = Math.ceil(totalSamples / samplesPerSlice); // 按照每一段需要截取的采样数将数据切分成 5 段 for (let i = 0; i < numSlices; i++) { const start = i * samplesPerSlice; const end = Math.min((i + 1) * samplesPerSlice, totalSamples); const slice = wav.clone(); slice.data.samples = slice.data.samples.slice(start, end); // 将每一段数据编码成 wav 文件并保存 const writer = new WaveFileWriter(); writer.write(slice, 'audio/wav'); writer.save(`slice-${i}.wav`); } ``` 注意,上述代码使用的 WaveFile 和 WaveFileWriter 都是基于 js-audio-recorder 的辅助库,需要先进行安装和导入。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值