简体   繁体   English

页面重新加载后,文本到语音代码不再起作用?

[英]Text to speech code doesn't work anymore after page reload?

I am trying to add a text to speech button to my website and another button that stops it again.我正在尝试向我的网站添加一个文本到语音按钮和另一个再次停止它的按钮。 It worked perfectly before until I reloaded the page, then it didn't do anything anymore.在我重新加载页面之前它一直运行良好,然后它不再执行任何操作。

So I tried adding window.onload= function but then it just starts reading as soon as I reload the page.所以我尝试添加window.onload= function 但是当我重新加载页面时它就开始读取。 but I want it to only read if you click the button and stop when the stop button is pressed.但我希望它只在您单击按钮时读取并在按下停止按钮时停止。 I don't understand what I am doing wrong especially because it used to work sometimes and then it didn't again even when I didn't really change the code.我不明白我做错了什么,特别是因为它过去有时会工作,然后即使我没有真正更改代码也不会再工作。

<script>
  window.speechSynthesis.cancel();

  function textToSpeech() {
    const speech = new SpeechSynthesisUtterance();
    let voices = speechSynthesis.getVoices();
    let convert = document.getElementById("text").innerHTML;
    speech.text = convert;
    speech.volume = 2;
    speech.rate = 1;
    speech.pitch = 1;
    speech.voice = voices[1];
    speechSynthesis.speak(speech);
  }

  function stop() {
    window.speechSynthesis.cancel();
  }
  speakBtn.addEventListener('click', textToSpeech);
  cancelBtn.addEventListener('click', stop);
</script>
<input type="button" id="1200196725" value="Speak" style="float: left; 
background-color:#00a2ab;
display:inline-block;
padding:0.3em 1.2em;
margin:0 0.3em 0.3em 0;
border-radius:2em;
box-sizing: border-box;
text-decoration:none;
font-family:'Roboto',sans-serif;
font-weight:300;
color:#FFFFFF;">
<input type="button" id="1731941681" value="Stop" style="float: left;background-color:#d4004b;
display:inline-block;
padding:0.3em 1.2em;
margin:0 0.3em 0.3em 0;
border-radius:2em;
box-sizing: border-box;
text-decoration:none;
font-family:'Roboto',sans-serif;
font-weight:300;
color:#FFFFFF;">
<p id="1112939208" style="display:none">
  my text here
</p>

You're adding eventListeners on buttons that haven't been defined it seems.您在似乎尚未定义的按钮上添加 eventListeners。 Try adding this to your code.尝试将此添加到您的代码中。 (And maybe give them more sensible id's) (也许给他们更明智的身份证)

const speakBtn = document.getElementById('1200196725');
const cancelBtn = document.getElementById('1731941681');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM