You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置SpeechSynthesisUtterance的voice属性避免类型错误?

正确设置SpeechSynthesisUtterance的voice属性解决类型错误

这个错误的核心原因是:SpeechSynthesisUtterance的voice属性仅接受SpeechSynthesisVoice类型的对象,直接赋值数字、字符串等其他类型会触发类型转换失败。

正确设置步骤

1. 获取系统可用语音列表

浏览器的语音列表是异步加载的,直接调用speechSynthesis.getVoices()可能返回空数组,需要通过voiceschanged事件监听加载完成:

let availableVoices = [];

// 监听语音列表加载完成
speechSynthesis.onvoiceschanged = () => {
  availableVoices = speechSynthesis.getVoices();
  // 这里可以初始化下拉选择框,把语音名称作为选项值
};

2. 匹配并赋值SpeechSynthesisVoice对象

从获取到的语音列表中,通过name、lang或voiceURI等属性找到目标语音对象,再赋值给voice属性:

示例1:直接指定语音名称
const utterance = new SpeechSynthesisUtterance('hi');
// 查找名称为"Google US English"的语音
const targetVoice = availableVoices.find(voice => voice.name === "Google US English");

if (targetVoice) {
  utterance.voice = targetVoice;
  speechSynthesis.speak(utterance);
} else {
  console.log("目标语音不存在");
}
示例2:下拉框选择场景(对应错误中的changeSpeaker事件)
// 假设下拉框选项的value是语音名称
function changeSpeaker(e) {
  const selectedVoiceName = e.target.value;
  const targetVoice = availableVoices.find(voice => voice.name === selectedVoiceName);
  
  if (targetVoice) {
    // 假设已有全局或局部的utterance实例
    utterance.voice = targetVoice;
  }
}

关键注意事项

  • 绝对不能给voice属性赋值非SpeechSynthesisVoice类型的值
  • 必须等待voiceschanged事件触发后,才能获取到完整的可用语音列表
  • 不同浏览器的可用语音名称、lang属性可能有差异,匹配时尽量用多个条件(比如同时匹配lang和name)提高兼容性

内容的提问来源于stack exchange,提问作者user22128331

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:22:44