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 实例来定义要朗读的文本和其他参数。
以下是一个基础示例:
这是一段要被朗读的文字。
document.getElementById('speak').onclick = function() { const text = document.getElementById('text').innerText; const utterance = new SpeechSynthesisUtterance(text); speechSynthesis.speak(utterance);};
设置语速、音调和音量
你可以自定义语音的播放效果,包括语速、音调和音量,使朗读更自然或符合特定需求。
立即学习“前端免费学习笔记(深入)”;
支持的属性有:
utterance.rate:语速,范围通常是 0.1 到 10,默认为 1 utterance.pitch:音调,范围 0 到 2,默认为 1 utterance.volume:音量,范围 0 到 1,默认为 1
示例代码:
Speech Studio
微软语音服务,提供语音到文本、文本到语音和语音翻译功能。
30 查看详情
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():取消当前和队列中的所有朗读
例如添加“停止”按钮:
基本上就这些。Speech Synthesis API 在现代浏览器中支持良好(Chrome、Edge、Firefox、Safari 部分支持),适合用于辅助功能、教育应用或交互式网页中。实际使用时建议加入浏览器兼容性判断,并提供备用方案。
以上就是html5使用speech synthesis实现文本朗读 html5使用语音合成API的示例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/598039.html
微信扫一扫
支付宝扫一扫