

新闻资讯
技术学院SpeechSynthesis需先检测navigator.speechSynthesis是否存在并监听voiceschanged事件确保音色加载完成;iOS Safari不支持,Chrome/Edge需用户交互后才启用,Firefox需手动开启配置。
Web Speech API 的语音合成功能依赖 SpeechSynthesis 接口,但它不是所有浏览器都默认启用,部分移动端(如 iOS Safari)完全不支持。调用前必须先检测是否存在且就绪:
navigator?.speechSynthesis 存在 ≠ 可用:需监听 voiceschanged 事件后再获取音色列表,否则 getVoices() 可能返回空数组DOMException: The operation is insecure
media.webspeech.synth.enabled(about:config),否则 navigator.speechSynthesis 为 undefined

if ('speechSynthesis' in navigator) {
const synth = window.speechSynthesis;
// 等待音色加载完成
synth.onvoiceschanged = () => {
const voices = synth.getVoices();
console.log('可用音色数量:', voices.length);
};
} else {
console.error('当前浏览器不支持 Web Speech API 语音合成');
}SpeechSynthesisVoice 不是全局配置,而是绑定在每个 SpeechSynthesisUtterance 实例上。不同语言/系统预装的音色数量差异极大(Windows Chrome 常有 10+ 个,macOS Safari 通常仅 2–3 个),不能硬编码索引取值。
find() 按 lang 和 name 匹配,例如 voice.lang.startsWith('zh-CN') 比 voice.name === 'Microsoft Zira Desktop' 更可靠rate 范围是 0.1–10,但超过 2.0 后语音易失真;pitch 0–2 之间较自然;volume 0–1,设为 0 就是静音synth.speak(utterance) 之前,之后修改无效const utterance = new SpeechSynthesisUtterance('你好,今天天气不错');
const voices = speechSynthesis.getVoices();
const chineseVoice = voices.find(v => v.lang.includes('zh-CN')) || voices[0];
utterance.voice = chineseVoice;
utterance.rate = 0.9;
utterance.pitch = 1.1;
utterance.volume = 0.8;
speechSynthesis.speak(utterance);SpeechSynthesis 是单例,所有 utterance 共享同一播放队列。控制逻辑不作用于单个实例,而是对整个合成器状态操作:
speechSynthesis.pause() 暂停当前正在播放的 utterance,resume() 恢复——但若队列中还有后续任务,恢复后会继续播下一个speechSynthesis.cancel() 清空整个队列(包括已暂停的),且不会触发 onend 回调speechSynthesis.getVoices() 无用,真正要用的是 speechSynthesis.pending、speechSynthesis.speaking、speechSynthesis.paused 这三个只读状态位判断当前状态这些问题基本都源于生命周期管理不当或复用 utterance 实例:
onend 不触发:utterance 被 GC 回收了——必须把实例赋给变量(如 let u = new SpeechSynthesisUtterance(...)),否则回调无法绑定\u200B),建议用 text.trim().replace(/\s+/g, ' ') 预处理speak() 只播一次:默认行为是追加到队列,需先 cancel() 再 speak;或者设 utterance.addEventListener('end', () => { /* 下一句 */ }) 串行控制音色加载、用户交互权限、实例生命周期——这三个环节任一出问题,语音就卡住不动。别猜,先查 speechSynthesis.pending 和 console.log(speechSynthesis.getVoices())。