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>
你可以自定义语音的播放效果,包括语速、音调和音量,使朗读更自然或符合特定需求。
立即学习“前端免费学习笔记(深入)”;
支持的属性有:
示例代码:
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);
可以对正在或即将播放的语音进行控制:
例如添加“停止”按钮:
<button onclick="speechSynthesis.cancel();">停止朗读</button>
基本上就这些。Speech Synthesis API 在现代浏览器中支持良好(Chrome、Edge、Firefox、Safari 部分支持),适合用于辅助功能、教育应用或交互式网页中。实际使用时建议加入浏览器兼容性判断,并提供备用方案。
以上就是html5使用speech synthesis实现文本朗读 html5使用语音合成API的示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号