SpeechSynthesisUtterance:lang 属性

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上使用。自 2018 年 9 月以来,它已在各种浏览器中推出。

SpeechSynthesisUtterance 接口的 lang 属性用于获取和设置语音合成文本的语言。

如果未设置,则会使用应用程序的语言(即 <html> 标签的 lang 属性值),如果该值也未设置,则使用用户代理的默认语言。

一个字符串,表示 BCP 47 语言标签

示例

js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");

const voices = synth.getVoices();

// …

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (const voice of voices) {
    if (voice.name === selectedOption) {
      utterThis.voice = voice;
    }
  }
  utterThis.lang = "en-US";
  synth.speak(utterThis);
  inputTxt.blur();
};

规范

规范
Web Speech API
# dom-speechsynthesisutterance-lang

浏览器兼容性

另见