TML 中添加 Text-to-Speech 功能,首先需要使用 JavaScript创建 SpeechSynthesisUtterance 对象,并设置要朗读的文本。然后,使用SpeechSynthesis对象的speak()方法触发阅读。以下是一个基本示例:
<button onclick="speak()">点击朗读</button>
<script>
function speak() {
const utterance = new SpeechSynthesisUtterance();
utterance.text = "你好,欢迎使用Text-to-Speech功能!";
window.speechSynthesis.speak(utterance);
}
</script>
在代码中,“text”属性是设置要阅读的内容的关键词,而“SpeechSynthesisUtterance”和“SpeechSynthesis”分别是创建文本语音对象和触发它的库。请注意,浏览器需要用户授权才能调用Text-to-Speech功能。
此外,您还可以根据需要添加其他参数,例如语速、音高、音量、语言等。例如,设置语音为英语:
utterance.lang = 'en-US';
在HTML中将其应用类似如下:
<button onclick="speak()">点击朗读</button>
<script>
function speak() {
const utterance = new SpeechSynthesisUtterance();
utterance.text = "Hello, welcome to use Text-to-Speech feature!";
utterance.lang = 'en-US'; // 设置语言为英语
window.speechSynthesis.speak(utterance);
}
</script>
综上,在 HTML 中添加 Text-to-Speech 功能的基本步骤是创建 SpeechSynthesisUtterance 对象、设置要朗读的文本和其他可选参数,然后触发阅读。