<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Speech Recognition</title>
</head>
<body>
<input type="text" id="sendInput" placeholder="Recognized text will appear here">
<button id="speechButton">Hold to Speak</button>
<script>
let recognition;
let isListening = false;
function initSpeechRecognition() {
navigator.permissions.query({ name: "microphone" }).then((result) => {
console.log("Microphone Permission:", result.state);
});
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
alert("Your browser does not support Speech Recognition.");
return;
}
recognition = new SpeechRecognition();
recognition.lang = "en-US";
recognition.interimResults = false; // Only get final results
recognition.continuous = false; // Stop after each speech
recognition.onstart = () => console.log("🎙️ Speech recognition started...");
recognition.onspeechstart = () => console.log("🎤 Detected speech...");
recognition.onspeechend = () => console.log("🛑 Speech ended...");
recognition.onresult = (event) => {
console.log("🔊 Recognized:", event.results[0][0].transcript);
document.getElementById("sendInput").value += event.results[0][0].transcript + " ";
};
recognition.onerror = (event) => console.error("❌ Speech recognition error:", event.error);
recognition.onend = () => console.log("⏹️ Speech recognition stopped.");
}
function startSpeechRecognition() {
if (!recognition) initSpeechRecognition();
if (!isListening) {
isListening = true;
recognition.start();
console.log("✅ Speech Recognition Started.");
}
}
function stopSpeechRecognition() {
if (recognition && isListening) {
isListening = false;
recognition.stop();
console.log("⏹️ Speech Recognition Stopped.");
}
}
// Button event listeners
const speechButton = document.getElementById("speechButton");
speechButton.addEventListener("mousedown", startSpeechRecognition);
speechButton.addEventListener("mouseup", stopSpeechRecognition);
speechButton.addEventListener("mouseleave", stopSpeechRecognition);
</script>
</body>
</html>
I am trying to use speech recognition but below code is not getting called.
recognition.onresult = (event) => {
console.log("🔊 Recognized:", event.results[0][0].transcript);
document.getElementById("sendInput").value += event.results[0][0].transcript + " ";
};