首页 > 解决方案 > 为什么以下 JavaScript 的 Web Speech API 不起作用?

问题描述

当我点击Speak按钮时,应用程序应该开始阅读段落中的文本。但什么也没有发生。对于测试,我添加了一个alert("Test"); 在textToSpeech()函数的开头,并且警报弹出正确,这意味着单击事件确实触发了,但其其余代码无法正常工作。问题:我可能在这里遗漏了什么,我们该如何解决?

更新

  1. 我正在使用Edge浏览器Windows10
  2. 在进行下面第 3 项中所述的一些更改后,它可以在 Google Chrome 上运行。
  3. 我应该添加在和Resume之间切换的按钮PauseResume
  4. MS Edge浏览器上,我仍然有一些下面描述的问题。
  5. 我能够进行如下一些改进:我发现的一个问题是我必须将<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>

标签: javascripttext-to-speechgoogle-speech-apigoogle-cloud-speech

解决方案


推荐阅读