首页 > 解决方案 > Web Speech API 无法在 Chrome for Android 中正确加载语音

问题描述

我有一个简单的应用程序,它应该以选定的语言读出输入字段中输入的文本: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),我预计是英语。

标签: javascriptandroidgoogle-chromespeechwebspeech-api

解决方案


您可以明确指定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" />


推荐阅读