vue的微信语音功能,录音+对接口返回amr音频播放

vue的微信语音功能,录音+对接口返回amr音频播放

最近的新项目需要调用微信的录音功能,但是后台又不给音频转码,无奈之下就踏上了研究前端音频编码器这东西。
参考的GitHub仓库——Recorder
参考的GitHub仓库——benz-amr-recorder
先上代码:
在index.html加载下面三个js

	<script type="text/javascript" src="./static/app/app-min.js"></script>
    <script src="./static/app/recorder-core.js"></script>
    <script type="text/javascript" src="./static/app/beta-amr.js"></script>

app-min.js对应的是下图这个文件,其他两个文件都可以在该仓库找到名字一样
在这里插入图片描述
然后在你需要播放amr音频的页面添加以下方法

// 加载音频的方法  voice参数是接口返回的amr链接.amr,这个需要后端的把微信的amr音频存储到本地再返回给前端
(该方法只能播放同源的音频链接)
loadDemoBtn(voice){
      // this.amr = new BenzAMRRecorder();
      this.loadDemoBtn1.setAttribute('disabled', true);
      this.loadAmrFile1.setAttribute('disabled', true);
      this.playBtn.setAttribute('disabled', true);
      const that = this;
      // http://localhost:8081/addons/yun_shop/static/app/mario.amr
      // https://dev1.yunzshop.com/addons/yun_shop/storage/app/public/business_card/3f91e0ce6866d86639e81aab8f4951a2_5.amr
      that.initWithUrl(voice).then((data)=> {
      // 把amr转码成WAV
        Recorder.amr2wav(data,function(blob){
          that.end(blob);
          console.log("已转码成wav播放");
        },function(msg){
          console.log("转码成wav失败:"+msg);
        });
        that.loadDemoBtn1.removeAttribute('disabled');
        that.loadAmrFile1.removeAttribute('disabled');
        that.playBtn.removeAttribute('disabled');
        // that.duration.innerHTML = that.amr.getDuration().toFixed(2) + '\'';
      });
    },
    
    // 把amr加载
    initWithUrl(url) {
      if (this._isInit || this._isInitRecorder) {
        throw new Error('AMR has been initialized. For a new AMR, please generate a new BenzAMRRecorder().');
      }

      const p = new Promise((resolve, reject) => {

        fetch(url, {
          method: 'GET',
          responseType: 'blob',
          headers: {'Content-Type': 'application/octet-stream'},
          credentials: 'include'
        })
          .then((response) => {
            if (response.ok) {
              response.blob().then(function(blob) {
                console.log(blob);
                resolve(blob);
              });
            }
          })
          .catch((err) => {
            reject(err);
          })

      });
      return p.then(blob => {
        return blob;
      });
    },

以上代码就可以播放微信录音的amr音频。

例子以后再放 先写到这里

猜你喜欢

转载自blog.csdn.net/qq_38188485/article/details/89635538
今日推荐