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

Web Speech API文本转语音配置voice参数时在utterThis.voice行报错求助

错误原因

SpeechSynthesisUtterance的voice属性不支持自定义构造的对象,必须传入window.speechSynthesis.getVoices()接口返回的原生语音实例。同时浏览器加载语音列表是异步操作,页面初始化时直接调用getVoices()通常会拿到空数组,需要监听voiceschanged事件确认语音加载完成后再使用。

修复后可运行代码

HTML 代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>

JS 代码

var synth = window.speechSynthesis;
var enUsVoice = null;

// 监听语音列表加载完成事件
synth.addEventListener('voiceschanged', function() {
  const allVoices = synth.getVoices();
  // 优先匹配目标语音,无匹配时兜底取任意en-US语音
  enUsVoice = allVoices.find(voice => voice.name === 'Google US English') 
    || allVoices.find(voice => voice.lang === 'en-US');
});

$('button').on('click', function(){
  // 兼容语音未加载完成的点击场景
  if (!enUsVoice) return alert('英文语音资源未加载完成,请稍后重试');
  var utterThis = new SpeechSynthesisUtterance('blue sky');
  utterThis.rate = 1;
  utterThis.pitch = 1;
  utterThis.voice = enUsVoice;
  synth.speak(utterThis);
});
补充说明

不同浏览器内置的语音名称存在差异,如果当前环境没有Google US English语音,代码会自动匹配其他可用的美式英语语音,保证功能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:06:03