Chrome浏览器为了屏蔽带声音的骚扰广告,从66版本后不再允许自动播放语音,我做的项目需要实时语音提示报警信息,网上搜索了好久都说不再支持自动播放,直到碰到一个大神提供建议设置Chrome浏览器允许声音自动播放:
前台JS代码如下:
let u = new SpeechSynthesisUtterance();
u.text="说点啥呢,点个赞再走呗"
u.lang='zh'
u.rate='1.2'
speechSynthesis.speak(u)
方法1:
在鼠标右击Chrome快捷图-->属性-->快捷方式-->目标加入"--autoplay-policy=no-user-gesture-required"即可
方法2:
在较老版本chrome地址栏中输入chrome://flags/
再搜索Autoplay policy
再在右侧的选项中设置为 No user gesture is required 即可
方法3:
如果是76-80=版本chrome设置:
搜索Touch Events API改成Automatic
设置后就可以使用Chrome自带的文字转语音工具了:
方法4:
自动升级到90版本,再次不可用,修改代码:
this.speecher = window.speechSynthesis
if (this.speecher.speaking) {
console.error('speechSynthesis.speaking');
this.speecher.cancel()
}
const voices = this.speecher.getVoices()
let utterThis = new SpeechSynthesisUtterance('给你最后一次机会,赶快说~')
utterThis.onend = function (event) {
console.log('SpeechSynthesisUtterance.onend');
}
utterThis.onerror = function (event) {
console.error('SpeechSynthesisUtterance.onerror');
}
utterThis.rate = '1.2'
for(let i = 0; i < voices.length ; i++) {
if(voices[i].name === 'Microsoft Huihui Desktop - Chinese (Simplified)') {
utterThis.voice = voices[i];
break;
}
}
this.speecher.speak(utterThis)
方法5.
升级到91版本再次不可用
决定放弃chrome自带播报,改用百度语音,切记前端工程所在服务器需要可用联外网
let message = '你好,百度,我放弃了我的最爱谷歌浏览器语音'
let url = "https://tts.baidu.com/text2audio?cuid=baike&lan=ZH&ctp=1&pdt=301&vol=9&rate=32&per=0&tex=" + encodeURI(message);
// baidu文字转语音
var voiceContent = new Audio(url);
voiceContent.src = url;
voiceContent.play();