html5的Speech Synthesis API可通过javaScript实现文本转语音。首先使用SpeechSynthesisUtterance定义文本,再调用speechSynthesis.speak()朗读;可设置rate、pitch、volume调节语速、音调、音量;通过getVoices()获取语音列表并选择特定语言(如中文);支持pause、resume、cancel控制播放;需监听onvoiceschanged事件以加载语音;兼容现代浏览器,建议添加兼容性处理。
html5 的 Speech Synthesis API 可以让网页将文本内容朗读出来,使用起来非常简单,无需依赖外部插件。通过 javascript 调用浏览器内置的语音合成功能,即可实现文本转语音(TTS)。
基本使用方法
Speech Synthesis API 的核心是 window.speechSynthesis 对象。你可以创建一个 SpeechSynthesisUtterance 实例来定义要朗读的文本和其他参数。
以下是一个基础示例:
<button id="speak">朗读文本</button> <p id="text">这是一段要被朗读的文字。</p> <script> document.getElementById('speak').onclick = function() { const text = document.getElementById('text').innerText; const utterance = new SpeechSynthesisUtterance(text); speechSynthesis.speak(utterance); }; </script>
设置语速、音调和音量
你可以自定义语音的播放效果,包括语速、音调和音量,使朗读更自然或符合特定需求。
立即学习“前端免费学习笔记(深入)”;
支持的属性有:
- utterance.rate:语速,范围通常是 0.1 到 10,默认为 1
- utterance.pitch:音调,范围 0 到 2,默认为 1
- utterance.volume:音量,范围 0 到 1,默认为 1
示例代码:
const utterance = new SpeechSynthesisUtterance(text); utterance.rate = 1.2; // 稍快一点 utterance.pitch = 1; // 正常音调 utterance.volume = 0.8; // 80% 音量 speechSynthesis.speak(utterance);
选择语音(支持多语言)
不同设备和浏览器提供的语音种类不同,可通过 speechSynthesis.getVoices() 获取可用语音列表。
注意:voiceschanged 事件需要监听,因为语音列表可能是异步加载的。
let voices = []; function loadVoices() { voices = speechSynthesis.getVoices(); } // 监听语音列表加载完成 speechSynthesis.onvoiceschanged = loadVoices; // 设置使用中文语音(如存在) const utterance = new SpeechSynthesisUtterance('你好,世界!'); const chineseVoice = voices.find(voice => voice.lang.includes('zh')); if (chineseVoice) { utterance.voice = chineseVoice; } speechSynthesis.speak(utterance);
控制朗读:暂停、继续和取消
可以对正在或即将播放的语音进行控制:
- speechSynthesis.pause():暂停朗读
- speechSynthesis.resume():恢复朗读
- speechSynthesis.cancel():取消当前和队列中的所有朗读
例如添加“停止”按钮:
<button onclick="speechSynthesis.cancel();">停止朗读</button>
基本上就这些。Speech Synthesis API 在现代浏览器中支持良好(chrome、edge、firefox、safari 部分支持),适合用于辅助功能、教育应用或交互式网页中。实际使用时建议加入浏览器兼容性判断,并提供备用方案。