如何用JavaScript实现语音合成_Web Speech API怎么用

SpeechSynthesis需先检测navigator.speechSynthesis是否存在并监听voiceschanged事件确保音色加载完成;iOS Safari不支持,Chrome/Edge需用户交互后才启用,Firefox需手动开启配置。

SpeechSynthesis 接口怎么初始化和检查可用性

Web Speech API 的语音合成功能依赖 SpeechSynthesis 接口,但它不是所有浏览器都默认启用,部分移动端(如 iOS Safari)完全不支持。调用前必须先检测是否存在且就绪:

  • navigator?.speechSynthesis 存在 ≠ 可用:需监听 voiceschanged 事件后再获取音色列表,否则 getVoices() 可能返回空数组
  • Chrome 和 Edge 在页面首次用户交互(如点击)后才允许触发合成,否则静音或报错 DOMException: The operation is insecure
  • Firefox 需要手动开启 media.webspeech.synth.enabledabout:config),否则 navigator.speechSynthesisundefined
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()langname 匹配,例如 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.pendingspeechSynthesis.speakingspeechSynthesis.paused 这三个只读状态位判断当前状态

常见错误:onend 不触发、中文乱码、连续调用只播一次

这些问题基本都源于生命周期管理不当或复用 utterance 实例:

  • onend 不触发:utterance 被 GC 回收了——必须把实例赋给变量(如 let u = new SpeechSynthesisUtterance(...)),否则回调无法绑定
  • 中文变英文或发音怪异:未正确匹配中文音色,或传入字符串含不可见 Unicode 字符(如零宽空格 \u200B),建议用 text.trim().replace(/\s+/g, ' ') 预处理
  • 连续 speak() 只播一次:默认行为是追加到队列,需先 cancel() 再 speak;或者设 utterance.addEventListener('end', () => { /* 下一句 */ }) 串行控制

音色加载、用户交互权限、实例生命周期——这三个环节任一出问题,语音就卡住不动。别猜,先查 speechSynthesis.pendingconsole.log(speechSynthesis.getVoices())