|
<!DOCTYPE html> |
|
<html> |
|
<head> |
|
<title>Speech Recognition</title> |
|
<style> |
|
#textbox { |
|
width: 100%; |
|
height: 100%; |
|
} |
|
</style> |
|
</head> |
|
<body> |
|
<textarea id="textbox"></textarea> |
|
<button onclick="startRecognition()">Start Recognition</button> |
|
<script> |
|
let recognition; |
|
let isListening = false; |
|
let inactivityTimeout; |
|
let previousSentences = []; |
|
|
|
function startRecognition() { |
|
if (!('webkitSpeechRecognition' in window)) { |
|
console.log('Speech Recognition is not supported by this browser.'); |
|
return; |
|
} |
|
if (isListening) { |
|
console.log('Already listening, please stop first.'); |
|
return; |
|
} |
|
recognition = new webkitSpeechRecognition(); |
|
recognition.lang = 'en-US'; |
|
recognition.interimResults = true; |
|
recognition.continuous = true; |
|
recognition.maxAlternatives = 5; |
|
|
|
recognition.onstart = function() { |
|
isListening = true; |
|
console.log('Listening...'); |
|
clearTimeout(inactivityTimeout); |
|
}; |
|
|
|
recognition.onresult = function(event) { |
|
let transcript = ''; |
|
let highestConfidence = 0; |
|
let mostConfidentTranscript = ''; |
|
for (let i = event.resultIndex; i < event.results.length; ++i) { |
|
if (event.results[i].isFinal) { |
|
for (let j = 0; j < event.results[i].length; ++j) { |
|
let result = event.results[i][j]; |
|
if (result.confidence > highestConfidence) { |
|
highestConfidence = result.confidence; |
|
mostConfidentTranscript = result.transcript; |
|
} |
|
} |
|
|
|
if (!previousSentences.includes(mostConfidentTranscript)) { |
|
previousSentences.push(mostConfidentTranscript); |
|
transcript += mostConfidentTranscript; |
|
document.getElementById('textbox').value += transcript + '\n'; |
|
} |
|
} else { |
|
transcript += event.results[i][0].transcript; |
|
document.getElementById('textbox').value = transcript; |
|
} |
|
} |
|
resetInactivityTimeout(); |
|
}; |
|
|
|
recognition.onend = function() { |
|
console.log('Recognition ended.'); |
|
stopRecognition(); |
|
}; |
|
|
|
navigator.mediaDevices.getUserMedia({ audio: true, video: false }) |
|
.then(function(stream) { |
|
recognition.start(); |
|
resetInactivityTimeout(); |
|
}) |
|
.catch(function(err) { |
|
console.log('Error accessing the microphone: ' + err); |
|
}); |
|
} |
|
|
|
function stopRecognition() { |
|
if (isListening) { |
|
isListening = false; |
|
recognition.stop(); |
|
clearTimeout(inactivityTimeout); |
|
console.log('Stopped listening.'); |
|
} |
|
} |
|
|
|
function resetInactivityTimeout() { |
|
clearTimeout(inactivityTimeout); |
|
inactivityTimeout = setTimeout(function() { |
|
stopRecognition(); |
|
}, 5000); |
|
} |
|
</script> |
|
</body> |
|
</html> |