目前只支持前三种语音播放
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字转语音</title>
</head>
<body>
<input class="input_a" type="text">
<button class="button_a">播放第1种</button>
<button class="button_b">播放第2种</button>
<button class="button_c">播放第3种</button>
</body>
<script>
var input_a = document.querySelector(".input_a")
var button_a = document.querySelector(".button_a")
var button_b = document.querySelector(".button_b")
var button_c = document.querySelector(".button_c")
input_a.value = '你好,我是语音合成器'
// 创建一个SpeechSynthesisUtterance实例
const utterance = new SpeechSynthesisUtterance();
// 设置语言
utterance.lang = 'zh-CN';
// 设置音量(0到1之间)
utterance.volume = 1;
// 设置语速(0.1到10之间)
utterance.rate = 1;
// 设置音调(0.1到2之间)
utterance.pitch = 1;
var voices
speechSynthesis.addEventListener('voiceschanged', () => {
voices = speechSynthesis.getVoices();
console.log(voices);
utterance.voice = voices[0]
})
button_a.onclick = () => {
let text = input_a.value
console.log('开始1', text);
utterance.text = text
console.log(voices[0]);
utterance.voice = voices[0]
speechSynthesis.speak(utterance);
}
button_b.onclick = () => {
let text = input_a.value
console.log('开始2', text);
utterance.text = text
console.log(voices[1]);
utterance.voice = voices[1]
speechSynthesis.speak(utterance);
}
button_c.onclick = () => {
let text = input_a.value
console.log('开始3', text);
utterance.text = text
console.log(voices[2]);
utterance.voice = voices[2]
speechSynthesis.speak(utterance);
}
</script>
</html>