工作中遇到,浏览器不能合成语音;
解决思路,合成失败时, 循环合成列表, 找到能正常合成的为止;
对于一直不能合成的浏览器, 设置开关, 关闭循环功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
</head>
<body>
<div id="app" style="position:relative;top:350px;">
<button @click="getMessage()">开始</button>
<button @click="overPlay()">停止</button>
</div>
<script>
const synth = window.speechSynthesis;
const utterThis = new SpeechSynthesisUtterance();
var voiceInd = 0
var voices
const appData = {
data() {
return {
voiceInd: 0,
playSate:false
}
},
methods: {
getMessage() {
var text = "测试中文语音";// msg
utterThis.text = text; // 文字内容
utterThis.lang = "zh-CN"; // 使用的语言:中文
utterThis.volume = 1; // 声音音量:1
utterThis.rate = 1; // 语速:1
utterThis.pitch = 1; // 音高:1
utterThis.onerror = (event) => {
console.log(`An error has occurred with the speech synthesis: ${event.error}`, this.voiceInd);
// 继续找
var voices = synth.getVoices()
if (this.voiceInd + 1 >= voices.length) {
console.log(`error times`, this.voiceInd);
} else {
this.playVoice(this.voiceInd + 1);
}
}
utterThis.onstart = (event) => {
console.log('onstart', event);
this.playSate = true
}
utterThis.onend = (event) => {
//console.log(`onend `, event);
if(playSate){
this.playVoice(this.voiceInd);
}
}
},
playVoice(vInd) {
var voice;
console.log('pBTN', vInd, voices)
// console.log(JSON.stringify(voices, ["voiceURI", "lang", "localService"]));
if (voices == undefined || voices.length == 0) {
voices = synth.getVoices();
// console.log(`赋值voices:aaa`, voices, voices.length)
} else {
// console.log(`voices.length:${voices.length}`)
}
if (voice == undefined || voice == null) {
console.log(`赋值voices:aaa`, voices)
for (var i = vInd; i < voices.length; i++) {
if (voices[i]['localService'] && voices[i]['lang'] == "zh-CN") {
console.log(`i==`, i)
voice = voices[i];
break;
}
this.voiceInd = i
}
console.log(`33333:`, this.voiceInd)
utterThis.voice = voice;
// console.log(utterThis.voice);
synth.speak(utterThis); // 播放
this.playState = true
} else {
// console.log("开始播放")
utterThis.voice = voice;
// console.log(utterThis.voice);
synth.speak(utterThis); // 播放
}
},
replay(utterThis) {
console.log("重复播放")
synth.speak(utterThis); // 播放
},
overPlay() {
this.playState = false
synth.cancel()
}
}
}
Vue.createApp(appData).mount('#app')
</script>
</body>
</html>