Created
April 19, 2024 12:58
-
-
Save fzn0x/1291bce3e41d4f36a434fb7f1b6e8972 to your computer and use it in GitHub Desktop.
Voice Recognition in Modern Browsers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
</head> | |
<body> | |
<div class="output"></div> | |
</body> | |
<script> | |
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.webkitSpeechRecognition; | |
window.SpeechGrammarList = window.SpeechGrammarList || window.webkitSpeechGrammarList; | |
if (window.SpeechRecognition == undefined) { | |
alert("Speech Recognition is not supported in your browser"); | |
} else { | |
const grammar = | |
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; | |
const recognition = new SpeechRecognition(); | |
const speechRecognitionList = new SpeechGrammarList(); | |
speechRecognitionList.addFromString(grammar, 1); | |
recognition.grammars = speechRecognitionList; | |
recognition.continuous = true; | |
recognition.lang = "en-US"; | |
recognition.interimResults = true; | |
recognition.maxAlternatives = 1; | |
const diagnostic = document.querySelector(".output"); | |
const bg = document.querySelector("body"); | |
recognition.start(); | |
console.log("Ready to receive a color command."); | |
recognition.onresult = (event) => { | |
// Set a new timeout that will trigger if no new results come in the next 10 seconds | |
resultTimeout = setTimeout(() => { | |
recognition.stop(); | |
console.log('Recognition stopped due to inactivity.'); | |
}, 10000); | |
setTimeout(() => { | |
const color = event.results[0][0].transcript; | |
diagnostic.textContent = `Result received: ${color}`; | |
bg.style.backgroundColor = color; | |
}, 3000); | |
}; | |
recognition.onend = () => { | |
// Clear the timeout when recognition stops to clean up | |
clearTimeout(resultTimeout); | |
console.log('Recognition ended.'); | |
recognition.start(); | |
}; | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment