项目中需要搞个实时订单推送提醒,通过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(); },