This JavaScript code is for creating a voice-controlled virtual assistant that can perform actions like greeting, opening websites, and telling the time or date based on voice commands. Let's break it down line by line:
1. Select DOM Elements:
let btn = document.querySelector("#btn");
let content = document.querySelector("#content");
let voice = document.querySelector("#voice");
btn: Selects an HTML element with theidof "btn" (likely a button that triggers the assistant to listen for commands).content: Selects an HTML element with theidof "content" (used to display information or responses).voice: Selects an HTML element with theidof "voice" (used for controlling voice visibility or elements).
2. speak() Function:
function speak(text) {
let text_speak = new SpeechSynthesisUtterance(text);
text_speak.rate = 1;
text_speak.pitch = 2;
text_speak.volume = 2;
text_speak.lang = "en-GB";
window.speechSynthesis.speak(text_speak);
}
This function converts text to speech:
SpeechSynthesisUtterance(text): Creates a speech object that will speak the providedtext.text_speak.rate = 1: Sets the speed of speech. 1 is the normal rate.text_speak.pitch = 2: Adjusts the pitch of the speech. Higher values make the voice higher-pitched.text_speak.volume = 2: Controls the volume. It should be between 0 and 1 (so this might be too high and won't work as expected).text_speak.lang = "en-GB": Sets the language of the speech (in this case, British English).window.speechSynthesis.speak(text_speak): Initiates the speech synthesis.
3. wishMe() Function:
function wishMe() {
if (!sessionStorage.getItem("greeted")) {
let day = new Date();
let hours = day.getHours();
if (hours >= 0 && hours < 12) {
speak("Good Morning, It's a pleasure to have you here!");
} else if (hours >= 12 && hours < 16) {
speak("Good afternoon, It's a pleasure to have you here!");
} else {
speak("Good Evening, It's a pleasure to have you here!");
}
sessionStorage.setItem("greeted", "true");
}
}
This function greets the user based on the time of day:
sessionStorage.getItem("greeted"): Checks if the greeting has been shown during this session. Ifgreetedis not found in the session storage, the greeting will be triggered.let day = new Date();: Creates a newDateobject to get the current date and time.let hours = day.getHours();: Gets the current hour (0–23).- Based on the hour, it greets the user:
- Morning: 0–11
- Afternoon: 12–15
- Evening: 16–23
- After greeting, it stores
"greeted": "true"insessionStorageso it won't greet again during the current session.
4. window.addEventListener('load',()=>{ wishMe() })
window.addEventListener('load',()=>{ wishMe() }): When the page is fully loaded, thewishMe()function is called to greet the user.
5. Speech Recognition Setup:
let speechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = new speechRecognition();
let speechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition: This checks for the availability of the Speech Recognition API, either usingSpeechRecognition(for modern browsers) orwebkitSpeechRecognition(for older browsers).let recognition = new speechRecognition();: Creates a new instance of the speech recognition object.
6. Handle Speech Recognition Results:
recognition.onresult = (event) => {
let currentIndex = event.resultIndex;
let transcript = event.results[currentIndex][0].transcript;
content.innerText = "";
takeCommand(transcript.toLowerCase());
}
recognition.onresult: This event is triggered when the speech recognition system has successfully captured speech input.let currentIndex = event.resultIndex;: Retrieves the index of the speech result from the event.let transcript = event.results[currentIndex][0].transcript;: Extracts the actual speech text (transcript) from the recognition result.content.innerText = "";: Clears any previous content in the "content" element.takeCommand(transcript.toLowerCase());: Converts the transcript to lowercase and passes it to thetakeCommand()function for further processing.
7. Start Speech Recognition on Button Click:
btn1.addEventListener("click", () => {
recognition.start();
voice.style.display = "block";
btn1.style.display = "none";
btn2.style.display = "none";
});
btn1.addEventListener("click", () => { ... }): Adds a click event listener tobtn1(probably a "Start Listening" button).recognition.start();: Starts the speech recognition process.voice.style.display = "block";: Makes the "voice" element visible (likely to indicate that the assistant is listening).btn1.style.display = "none";: Hides the "Start Listening" button.btn2.style.display = "none";: Hides another button (perhaps a "Stop" button).
8. Process Voice Command:
function takeCommand(message) {
voice.style.display = "none";
btn1.style.display = "flex";
if (message.includes("hello") || message.includes("hey")) {
speak("Hello!, How can I assist you?");
} else if (message.includes("who are you")) {
speak("I am a virtual assistant, created by Seema, Naila, and others.");
} else if (message.includes("open youtube")) {
speak("Opening YouTube...");
window.open("https://youtube.com/", "_blank");
} else if (message.includes("open google")) {
speak("Opening Google...");
window.open("https://google.com/", "_blank");
} else if (message.includes("open facebook")) {
speak("Opening Facebook...");
window.open("https://facebook.com/", "_blank");
} else if (message.includes("open instagram")) {
speak("Opening Instagram...");
window.open("https://instagram.com/", "_blank");
} else if (message.includes("open calculator")) {
speak("Opening calculator...");
window.open("calculator://");
} else if (message.includes("open whatsapp")) {
speak("Opening WhatsApp...");
window.open("whatsapp://");
} else if (message.includes("time")) {
let time = new Date().toLocaleString(undefined, { hour: "numeric", minute: "numeric" });
speak(time);
} else if (message.includes("date")) {
let date = new Date().toLocaleString(undefined, { day: "numeric", month: "short" });
speak(date);
} else {
let finalText = "This is what I found on the internet regarding " + message.replace("shipra", "") || message.replace("shifra", "");
speak(finalText);
window.open(`https://www.google.com/search?q=${message.replace("shipra", "")}`, "_blank");
}
btn2.style.display = "flex";
}
This function processes the voice message (received as message) and performs actions based on it:
voice.style.display = "none";: Hides the "voice" element once the command is processed.btn1.style.display = "flex";: Shows the "Start Listening" button again (perhaps after processing the command).- The function checks for specific phrases (like "hello", "who are you", "open youtube", etc.) and performs actions such as:
- Greeting the user.
- Opening specific websites (YouTube, Google, Facebook, Instagram, etc.).
- Showing the current time and date.
- Performing a Google search for a message if no specific command is matched.
9. Show "Stop Listening" Button:
btn2.style.display = "flex";
- After processing the command, this line shows a second button (
btn2), likely a "Stop Listening" or confirmation button.
Conclusion:
This script combines speech recognition and speech synthesis to create a virtual assistant that can listen for voice commands and respond with actions or spoken replies. The assistant can greet the user, open websites, and provide real-time information like time and date based on the user's input.