javascript - 为什么以下 JavaScript 的 Web Speech API 不起作用?
问题描述
当我点击Speak
按钮时,应用程序应该开始阅读段落中的文本。但什么也没有发生。对于测试,我添加了一个alert("Test")
; 在textToSpeech()
函数的开头,并且警报弹出正确,这意味着单击事件确实触发了,但其其余代码无法正常工作。问题:我可能在这里遗漏了什么,我们该如何解决?
更新:
- 我正在使用
Edge
浏览器Windows10
- 在进行下面第 3 项中所述的一些更改后,它可以在 Google Chrome 上运行。
- 我应该添加在和
Resume
之间切换的按钮Pause
Resume
- 在
MS Edge
浏览器上,我仍然有一些下面描述的问题。 - 我能够进行如下一些改进:我发现的一个问题是我必须将
<script>
标签移动到</body>
. 我发现的另一个问题是我必须speechSynthesis.speak(speech);
符合window.
. 例如:window.speechSynthesis.speak(speech);
。暂停和取消方法相同。但是,在 MS Edge 浏览器上,整个应用程序仍然无法正常运行。例如,您可以在讲话开始时暂停,但是当您Speak
再次单击时,声音会失真。您必须刷新浏览器才能恢复真实的声音(而不是失真的声音)。
HTML 文件:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>The script element</h1>
<input type="button" id="speakBtn" value="Speak">
<input type="button" id="pauseBtn" value="Pause">
<input type="button" id="cancelBtn" value="Cancel">
<p id="textID">
SQL Managed Instance gives you an instance of SQL Server but removes much of the overhead of managing a virtual machine.
</p>
<script>
function textToSpeech() {
//alert("Test"); //for test only.
const speech = new SpeechSynthesisUtterance();
let voices = speechSynthesis.getVoices();
let convert = document.getElementById("textID").innerHTML;
speech.text = convert;
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
speech.voice = voices[1];
speechSynthesis.speak(speech);
}
function pause() {
window.speechSynthesis.pause();
}
function stop() {
window.speechSynthesis.cancel();
}
speakBtn.addEventListener('click', textToSpeech);
pauseBtn.addEventListener('click', pause);
cancelBtn.addEventListener('click', stop);
</script>
</body>
</html>
解决方案
推荐阅读
- reactjs - 如何在 React.js 中获取每个项目的值
- linux - 手动 fsck 卡住(centos)
- javascript - Javascript 在 HTML 之前运行,即使在正文末尾
- filter - 报表生成器 Tablix 过滤器 1 数据集不在另一个数据集中
- c++ - 无法打开与 libprotobuf 3.5.0(Google 协议缓冲区)静态链接的共享库
- javascript - React + MaterialUI 显示带有身份验证的 JPEG 流
- python - 如何在 Python 中将类对象转换为 JSON
- python - 如何使用 Pandas read_csv() 读取包含特定字符串的特定行?
- ios - 日期格式化结果
- mongodb - 如何使用聚合在 MongoDB 中编写以下查询?