Skip to content

Instantly share code, notes, and snippets.

@jasonclark
Last active September 29, 2015 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonclark/fef8d6afd0d19815f9bd to your computer and use it in GitHub Desktop.
Save jasonclark/fef8d6afd0d19815f9bd to your computer and use it in GitHub Desktop.
Web Speech API Demo/Example - Search Form Input - https://www.lib.montana.edu/~jason/files/web-speech-api-search-input/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Speech API demo</title>
<link rel="stylesheet" href="css/style.css">
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body id="home">
<h1>Web Speech API demo - Speak to Search</h1>
<form action="http://arc.lib.montana.edu/digital-collections/index.php">
<input type="search" id="q" name="q" results="5" autofocus autosave="unique" placeholder="search...">
<input id="talk" type="button" value="record">
</form>
<p id="message"></p>
<script type="text/javascript">
window.addEventListener('load', function() {
//set global speech and message variables
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition || null;
var msg = document.getElementById("message");
var q = document.getElementById("q");
//check for speech recognition API support
if (window.SpeechRecognition === null) {
//disable talk+record input
document.getElementById("talk").setAttribute('disabled', 'disabled');
msg.innerHTML = '<strong class="loading">Bummer… your browser does not support speech input. Type in your search and hit enter.</strong>';
} else {
var recognition = new window.SpeechRecognition();
//recognition.continuous = true; // keep processing input until stopped
//recognition.interimResults = true; // show interim results
recognition.lang = 'en-US'; // specify the language
recognition.onresult = function(event) {
if (event.results.length > 0) {
msg.innerHTML = '<strong class="loading">Hold on... running your search.</strong>';
q.value = event.results[0][0].transcript;
q.form.submit();
}
};
//set up event to start recognition when input is clicked/touched
document.getElementById("talk").addEventListener('click', function() {
recognition.start();
msg.innerHTML = '<strong class="loading">Talk to me…</strong>';
});
//set error message if recognition fails
recognition.onerror = function(event) {
msg.innerHTML = '<strong class="loading">Could not hear you. Can you try again?</strong>';
console.log('Recognition error: ' + event.message);
};
}
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment