HTML5的SpeechSynthesis API可实现网页文字转语音。首先检测'speechSynthesis' in window支持情况,再通过new SpeechSynthesisUtterance()创建语音对象并调用speak()播放,可设置音量、语速、音调和语言等参数。由于getVoices()初始可能为空,需监听onvoiceschanged事件获取可用语音列表,并可据此选择特定语音如中文普通话。还支持pause、resume和cancel控制播放状态。关键在于处理语音列表异步加载及参数适配,适合语音播报与可访问性增强场景。

HTML5的SpeechSynthesis API可以让网页直接调用系统语音引擎,实现文字转语音(TTS)功能。使用它不需要引入外部库,兼容现代主流浏览器,适合做语音播报、可访问性增强等场景。
在使用API前,先判断当前浏览器是否支持:
if ('speechSynthesis' in window) {
// 支持语音合成
} else {
console.log('当前浏览器不支持语音合成');
}
使用 window.speechSynthesis.speak() 方法播放语音:
const utterance = new SpeechSynthesisUtterance('你好,这是语音合成示例');
speechSynthesis.speak(utterance);
SpeechSynthesisUtterance 是语音内容对象,可以设置文本、音调、语速、音量和发音语言等参数。
立即学习“前端免费学习笔记(深入)”;
你可以自定义语音输出效果:
const utterance = new SpeechSynthesisUtterance('欢迎使用语音合成');
utterance.volume = 1; // 音量:0 到 1
utterance.rate = 1; // 语速:0.1 到 10
utterance.pitch = 1; // 音调:0 到 2
utterance.lang = 'zh-CN'; // 语言:中文普通话
调整 rate 可让语音更慢或更快,适合不同用户习惯。
不同设备支持的语音不同,可通过以下方式获取系统可用语音:
// 等待语音列表加载完成
speechSynthesis.getVoices().forEach(voice => {
console.log(voice.name, voice.lang, voice.default ? '默认' : '');
});
注意:getVoices() 初始可能返回空数组,需监听 voiceschanged 事件:
if (speechSynthesis.getVoices().length === 0) {
speechSynthesis.onvoiceschanged = () => {
const voices = speechSynthesis.getVoices();
// 此处可选择特定语音
};
}
比如想使用中文女声:
const utterance = new SpeechSynthesisUtterance('使用中文语音播报');
const voices = speechSynthesis.getVoices();
const chineseVoice = voices.find(voice => voice.lang === 'zh-CN');
if (chineseVoice) {
utterance.voice = chineseVoice;
}
speechSynthesis.speak(utterance);
提供暂停、恢复和取消功能:
speechSynthesis.pause(); // 暂停 speechSynthesis.resume(); // 恢复 speechSynthesis.cancel(); // 取消全部语音
可用于交互式应用,如点击按钮停止播报。
基本上就这些。SpeechSynthesis API简单易用,关键是处理好语音列表异步加载问题,并根据用户需求调节语速和语言。不复杂但容易忽略细节。
以上就是HTML5语音合成API怎么用_HTML5SpeechSynthesisAPI实现语音合成的方法的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号