JavaScript语音合成基于Web Speech API的SpeechSynthesis接口,支持离线使用;需检测兼容性、监听voiceschanged事件获取音色列表,再创建并配置SpeechSynthesisUtterance实例,通过speak()等方法控制播放,且必须由用户交互触发。
JavaScript 实现语音合成,核心是使用浏览器原生的 Web Speech API 中的 SpeechSynthesis 接口。它无需第三方库、不依赖网络(离线可用),只要浏览器支持(Chrome、Edge、Safari 17.4+、Firefox 部分支持),就能让网页“说话”。
SpeechSynthesis 是一个单例对象,通过 window.speechSynthesis 访问。使用前建议先确认兼容性:
if ('speechSynthesis' in window)
const synth = window.speechSynthesis;
synth.onvoiceschanged = () => { console.log(synth.getVoices()); };(注意:首次调用 getVoices() 可能为空,需等事件触发后才返回可用音色列表)不同系统和浏览器预装的语音不同(如中文常用 “Microsoft Yaoyao”、“Tingting”、“Xiaoyi”)。你需要手动匹配语言和
voiceName:
const voices = synth.getVoices();
const cnVoice = voices.find(v => v.lang.includes('zh') || v.name.includes('Yaoyao') || v.name.includes('Xiaoyi'));
const utterance = new SpeechSynthesisUtterance('你好,我在用浏览器说话');
utterance.voice = cnVoice; utterance.rate = 1.0; utterance.pitch = 1.2; utterance.volume = 0.9;(rate 范围 0.1–10,pitch 0–2,volume 0–1)语音不是立即播放,而是加入合成队列。控制逻辑要靠事件和方法配合:
synth.speak(utterance);
synth.pause();
synth.resume();
synth.cancel();
utterance.onstart、onend、onerror、onpause,可用于更新 UI 状态(如按钮文字从“播放”变“暂停”)实际开发中容易踩坑:
speak() 必须由用户手势(如 click、touchend)触发,不能在页面加载或定时器里直接调用getVoices() 初次可能为空,务必监听 voiceschanged 再取值synth.cancel(),防止多条语音叠加