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