谷歌和火狐浏览器 new Audio 无效解决方案,20190816亲测有效。

项目中需要搞个实时订单推送提醒,通过websocket接收到消息后,播放这语音;结果发现主推的谷歌浏览器不能顺利播放音频,研究了两天,终于可以用了,特此记录下。

 
谷歌和火狐浏览器新版的不允许自动播放音频,这里通过网上的方法,用AudioContext 可以解决。 

// 播放语音
playRemind() {
  const remindUrl = '自己语音地址'; // 此处用的线上地址,本地mp3格式通过打包后,格式不对,无法播放;(vue cli3)
  const isChrome = (/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)) || /Firefox/.test(navigator.userAgent);
  if (!isChrome) {
    const n = new Audio(remindUrl);
    n.src = remindUrl;
    const audioPlay = n.play();
    audioPlay
      .then(() => {
        console.log('可以自动播放');
        this.openNotify();
        n.play();
        n.oncanplaythrough = function() {
          n.play();
        };
      }).catch((err) => {
        console.log(err);
        console.log('不可以自动播放');
      });
  } else {
    const _this = this;
    console.log('进入谷歌/火狐浏览器~');
    window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
    try {
      const context = new window.AudioContext();
      let source = null;
      let audioBuffer = null;
      const xhr = new XMLHttpRequest(); // 通过XHR下载音频文件
      xhr.open('GET', remindUrl, true);
      xhr.responseType = 'arraybuffer';
      xhr.onload = function(e) { // 下载完成
        context.decodeAudioData(this.response, function(buffer) { // 解码成功时的回调函数
          audioBuffer = buffer;
          source = context.createBufferSource();
          source.buffer = audioBuffer;
          source.loop = false;
          source.connect(context.destination);
          source.start(0); // 立即播放
          _this.openNotify();
        }, function(e) { // 解码出错时的回调函数
          console.log('Error decoding file', e);
        });
      };
      xhr.send();
    } catch (e) {
      console.log('您的浏览器不支持播放语音!');
    }
  }
  // audio.play();
},
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值