Web Speech API not properly loading voices in Chrome for Android
Asked Answered
C

1

5

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.

Cephalic answered 15/5, 2020 at 9:50 Comment(0)
T
4

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" />
Timisoara answered 15/5, 2020 at 10:7 Comment(2)
perfect, thank you! adding the lang explicitly worked!Cephalic
Thanks for answering, seriously! It's such an odd error, setting .voice by itself on Google-voices is unsufficient, but works for the other voices. Good find.Rafaelita

© 2022 - 2024 — McMap. All rights reserved.