问题
I have a simple app that should read out text entered into an input field in a selected language: https://speech-synthesis-demo.glitch.me/
This seems to work well on desktop in multiple browsers. However, when I try to run it in Chrome for Android, it seems that changing the language has no effect, and only the default language is used (in my case, English).
For testing purposes, what I'm trying to do is test out counting in different languages. If you enter in the word 'one' for example in the app on any desktop browser, you'll hear the number one spoken in the selected language. However, on Chrome on my Android device, I only hear "one" spoke in English no matter what language is selected from the dropdown.
The code is exactly the same as the example on MDN for 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();
}
Oddly, the default language in the mobile browser is Bangla Bangladesh (bn_BD), which I expected to be English.
回答1:
You could explicitly specify 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" />
来源:https://stackoverflow.com/questions/61816398/web-speech-api-not-properly-loading-voices-in-chrome-for-android