首页 > 解决方案 > Javascript onoff按钮在聊天机器人中不起作用

问题描述

我是 Javascript 的新手,我想为网站构建一个使用语音识别和文本到语音的聊天机器人。我做了onoff按钮,但它不起作用。

我努力了:

while (value == "on") { 
  utterance.volume = 1; 
}

if (value == "on") {
  utterance.volume = 1;
} else {
  utterance.volume = 0;
}

但还是有问题。任何帮助

function onoff(){
    currentvalue = document.getElementById('onoff').value;
    if(currentvalue == "on"){
        document.getElementById("onoff").value="on";
    }else{
          document.getElementById("onoff").value="off";
    }
 return currentvalue;
}



function speak(string){
var soundonoff = onoff();
    var utterance = new SpeechSynthesisUtterance();
    utterance.voice = speechSynthesis.getVoices().filter(function(voice) 
    {return voice.name == "Alex";})[0];
    utterance.text = string;
    utterance.lang = "en-US"; 
    if (soundonoff == "on"){
    utterance.volume = 1; //0-1 interval
    }else{
    terance.volume = 0;
    }
    utterance.rate = 0.8;
    utterance.pitch = 1; //0-2 interval
    speechSynthesis.speak(utterance);

}

标签: javascripttext-to-speechchatbot

解决方案


为此,window.speechSynthesis 有暂停和恢复方法;

停止 :

speechSynthesis.pause(); // pauses utterances being spoken

见:暂停

恢复 :

  speechSynthesis.resume();  /// resumes utters ,

简历

取消(停止)

speechSynthesisInstance.cancel();

取消

根据您的情况,您可以调用这些方法

其他方法见 这里

更新: -

这是粗略的代码,根据您的要求更改

HTML:

<input type="checkbox" id="onoff" name="onoff" >On/Off<br>
<br/>
<input type="button" name="start" onclick="speak();" value ="start" > On/Off
 <br>

脚本 :

 <script>

  var synth = window.speechSynthesis;

   function speak(){
      var utterThis = new SpeechSynthesisUtterance('My pleasure, poke me up if you need more info.'); // 
      synth.speak(utterThis);
    }


 //// on check box change event call this 

   $('#onoff').change(function() {

      if($("#onoff").prop('checked') == true){
       speechSynthesis.pause();
      /// now I dont know you want to pause or stop, change it according to you 
       ///requirment 
       }  
     else {
         speechSynthesis.pause();
       }
  });
  </script>

GITHUB -示例项目


推荐阅读