javascript - Web Speech API 无法在 Chrome for Android 中正确加载语音

标签 javascript android google-chrome speech webspeech-api

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

这似乎在多种浏览器的桌面上运行良好。但是,当我尝试在 Chrome for Android 中运行它时,似乎更改语言没有效果,并且只使用默认语言(在我的例子中是英语)。

出于测试目的,我尝试做的是测试不同语言的计数。例如,如果您在任何桌面浏览器的应用程序中输入单词“一”,您将听到以所选语言说出的数字一。但是,在我的 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();
}

奇怪的是,移动浏览器的默认语言是 Bangla Bangladesh (bn_BD),我希望它是英语。

最佳答案

您可以明确指定 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);
<input id="input" type="text" value="one" />

关于javascript - Web Speech API 无法在 Chrome for Android 中正确加载语音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61816398/

相关文章:

javascript - 如何让文本在输入时到达拖动位置

java - 有没有办法在 Android Studio 中以编程方式对线性布局进行排序?

android - 将 JVM 单元测试作为 Android 插桩测试运行

javascript - Chrome 和 JS onclick 函数?

javascript - 是否可以自定义 Chrome 或其他浏览器以在所有打开的选项卡上运行本地 JavaScript 文件?

html - CSS 适用于 Chrome 但不适用于 IE

javascript - 刷新后,JS 脚本在部分 View 中不起作用

javascript - 如何在 Typescript 中使用 Alertify?

javascript - 防止用户在javascript中输入小数点前超过3个数字

android - intellij-core-26.0.1 的 Ionic 3 prod 发布构建问题