【问题标题】:Web Speech API not properly loading voices in Chrome for AndroidWeb Speech API 无法在 Chrome for Android 中正确加载语音
【发布时间】:2020-05-15 09:50:39
【问题描述】:

我有一个简单的应用程序,它应该以选定的语言读出输入到输入字段中的文本:https://speech-synthesis-demo.glitch.me/

这似乎在多个浏览器的桌面上运行良好。但是,当我尝试在 Chrome for Android 中运行它时,似乎更改语言没有任何效果,并且仅使用默认语言(在我的情况下为英语)。

出于测试目的,我正在尝试用不同的语言测试计数。例如,如果您在任何桌面浏览器上的应用程序中输入单词“one”,您将听到以所选语言说出的第一名。但是,在我的 Android 设备上的 Chrome 上,无论从下拉菜单中选择哪种语言,我都只能听到“一个”说英语。

代码与 MDN 上的 SpeechSynthesis 示例完全相同:https://developer.mozilla.org/en-US/docs/Web/API/Window/speechSynthesis

let synth = window.speechSynthesis;

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

let voices;

function populateVoiceList(){
  voices = synth.getVoices();

  for(var i=0; i< voices.length; i++){
    let option = document.createElement('option');
    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';

    option.setAttribute('data-lang', voices[i].lang);
    option.setAttribute('data-name', voices[i].name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

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

  let utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
  for(let i=0; i < voices.length; i++){
  if(voices[i].name === selectedOption){
    utterThis.voice = voices[i];
  }
  }
  synth.speak(utterThis);
  inputTxt.blur();
}

奇怪的是,移动浏览器的默认语言是孟加拉孟加拉语 (bn_BD),我原以为是英语。

【问题讨论】:

    标签: javascript android google-chrome speech webspeech-api


    【解决方案1】:

    您可以明确指定SpeechSynthesisUtterance.lang

    const input = document.querySelector("#input");
    const speechSynthesis = window.speechSynthesis;
    
    const speak = () => {
      let speechSynthesisUtterance = new SpeechSynthesisUtterance(input.value);
      speechSynthesisUtterance.lang = 'en-US';
    
      speechSynthesis.speak(speechSynthesisUtterance);
    }
    
    input.addEventListener("change", speak);
    &lt;input id="input" type="text" value="one" /&gt;

    【讨论】:

    • 完美,谢谢!添加 lang 明确有效!
    • 感谢您的回答,认真的!这是一个奇怪的错误,在 Google 语音上单独设置 .voice 是不够的,但适用于其他语音。很好的发现。
    猜你喜欢
    • 1970-01-01
    • 2016-10-31
    • 2020-06-12
    • 2015-04-05
    • 2013-05-30
    • 2021-01-31
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多