showing results for - "javascript virtual assistant scrip 5bt"
Aislynn
03 Jan 2020
1const startBtn = document.createElement("button");
2startBtn.innerHTML = "Start listening";
3const result = document.createElement("div");
4const processing = document.createElement("p");
5document.write("<body><h1>My Siri</h1><p>Give it a try with 'hello', 'how are you', 'what's your name', 'what time is it', 'stop', ... </p></body>"); 
6document.body.append(startBtn);
7document.body.append(result);
8document.body.append(processing);
9
10const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
11
12if (typeof SpeechRecognition === "undefined") {
13  startBtn.remove();
14  result.innerHTML = "<b>Browser does not support Speech API. Please download latest chrome.<b>";
15}
16
17const recognition = new SpeechRecognition();
18recognition.continuous = true;
19recognition.interimResults = true;
20
21function process(speech_text) {
22    return "....";
23}
24recognition.onresult = event => {
25   const last = event.results.length - 1;
26   const res = event.results[last];
27   const text = res[0].transcript;
28   if (res.isFinal) {
29      processing.innerHTML = "processing ....";
30      const response = process(text);
31      
32      const p = document.createElement("p");
33      p.innerHTML = `You said: ${text} </br>Siri said: ${response}`;
34      processing.innerHTML = "";
35      result.appendChild(p);
36      // add text to speech later
37   } else {
38      processing.innerHTML = `listening: ${text}`;
39   }
40}
41
42let listening = false;
43toggleBtn = () => {
44   if (listening) {
45      recognition.stop();
46      startBtn.textContent = "Start listening";
47   } else {
48      recognition.start();
49      startBtn.textContent = "Stop listening";
50   }
51   listening = !listening;
52};
53startBtn.addEventListener("click", toggleBtn);
54
55function process(rawText) {
56   // remove space and lowercase text
57   let text = rawText.replace(/\s/g, "");
58   text = text.toLowerCase();
59   let response = null;
60   switch(text) {
61      case "hello":
62         response = "hi, how are you doing?"; break;
63      case "what'syourname":
64         response = "My name's Siri.";  break;
65      case "howareyou":
66         response = "I'm good."; break;
67      case "whattimeisit":
68         response = new Date().toLocaleTimeString(); break;
69      case "stop":
70         response = "Bye!!";
71         toggleBtn(); // stop listening
72   }
73   if (!response) {
74      window.open(`http://google.com/search?q=${rawText.replace("search", "")}`, "_blank");
75      return "I found some information for " + rawText;
76   }
77   return response;
78}
79
80speechSynthesis.speak(new SpeechSynthesisUtterance(response));