javascript - 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),我预计是英语。
解决方案
您可以明确指定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 - Resizable Sidebar - Drag To Resize
- node.js - Refresh JWT 令牌实施的正确流程
- events - Acumatica - 如何从客户中的自定义字段更新客户位置中的自定义字段
- java - JFrame 更新因线程休眠而失败
- r - 根据R中数据框中的列条件创建向量
- node.js - Express 中完全准确的网址
- reactjs - 一起在两个不同的动画视图上执行动画
- compass-sass - 为什么这个基本的 SASS 文件没有编译?
- r - 向列表中的每个数据框添加一个变量,该变量等于数据框名称
- python - 在 Python 中的对象实例化期间使用构造函数参数变量名?