1. 程式人生 > >播放語音,支援谷歌瀏覽器自動播放

播放語音,支援谷歌瀏覽器自動播放

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
};