存在问题1 : 在google chrome 89版本之后 默认使用的线上服务来合成语音 所以在国内可能会没有声音
解决办法 : 通过getVoices 获取 localService为true 的字段 (localService = true 表示 使用本地合成服务)
getWindowVoice(){ // 获取浏览器中语音 (中文 + 本地服务)
return window.speechSynthesis.getVoices().find(item => item.localService && item.lang === 'zh-CN')
}
存在问题2 : google chrome 播放语音可能会卡住 所以无声音
解决办法 : 在播放语音之前先 调用一下cancel方法
window.speechSynthesis.cancel()
播放和停止函数
// 语音停止
handleStop(e) {
if(window.speechSynthesis){
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
msg.text = e;
msg.lang = "zh-CN";
synth.cancel(msg);
}
},
// 语音播报的函数
handleSpeak(text='你好啊!'){
if(window.speechSynthesis){
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
msg.text = text; // 文字内容
msg.lang = "zh-CN"; // 使用的语言:中文
msg.volume = 1; // 声音音量:1
msg.rate = 1; // 语速:1
msg.pitch = 1; // 音高:1
msg.voice = this.getWindowVoice() // 使用本地服务合成语音(若是获取不到 请异步获取, 加一个setTimeout)
synth.speak(msg); // 播放
}
},