播放语音,支持谷歌浏览器自动播放

1.最近的项目用到了语音播放的,调用的是百度语音合成语音的接口,接入后发现在谷歌浏览器会报错,其它浏览器可以正常播放。

2.通过搜索了解到在Chrome 66以上的最新浏览器中,自动播放的视频要么是静音视频,要么就是没有声音的视频,或者是用户手动点击后播放的有声视频

3.在HTML5中新增了 <video></video> <audio></audio>两个标签视频和音频,在谷歌浏览器中,这两个标签中的 "autoplay" 属性是无效的,通过控制js的play()也是无法自动播放,必须要用户自动点击播放才行.

4.解决办法:遇到需要播放音频的需求,我们不一定要使用audio标签,还可以用音频API AudioContext来帮助我们完成,以下的js便是调用百度语音并且支持自动播放的最终方法:

function speckText(str) {
    let url = 'https://tts.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcd&ie=UTF-8&vol=9&per=0&spd=5&pit=5&aue=3&tex=' + encodeURI(str);
    let isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    // var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=" + encodeURI(str);        // baidu
    // var url = "http://translate.google.cn/translate_tts?ie=UTF-8&tl=zh-CN&total=1&idx=0&textlen=19&prev=input&q=" + encodeURI(str); // google
    if (!isChrome) {
        var n = new Audio(url);
        n.src = url;
        n.play();
    } else {
         window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext ||
             window.msAudioContext;
         try {
             var context = new window.AudioContext();;
             var source = null;
             var audioBuffer = null;
             function playSound() {
                 source = context.createBufferSource();
                 source.buffer = audioBuffer;
                 source.loop = false;
                 source.connect(context.destination);
                 source.start(0); //立即播放
             }

             function initSound(arrayBuffer) {
                 context.decodeAudioData(arrayBuffer, function (buffer) { //解码成功时的回调函数
                     audioBuffer = buffer;
                     playSound();
                 }, function (e) { //解码出错时的回调函数
                     console.log('Error decoding file', e);
                 });
             }

             function loadAudioFile(url) {
                 var xhr = new XMLHttpRequest(); //通过XHR下载音频文件
                 xhr.open('GET', url, true);
                 xhr.responseType = 'arraybuffer';
                 xhr.onload = function (e) { //下载完成
                     initSound(this.response);
                 };
                 xhr.send();
             }
             loadAudioFile(url);
         } catch (e) {
             console.log('!Your browser does not support AudioContext');
         }
    }
}
module.exports = {
    speckText: speckText
};

  

猜你喜欢

转载自www.cnblogs.com/laterly/p/10168217.html