I use this speech recognition function to activate listening following a specific event, such as the end of an animation. Subsequently, it awaits user input and, based on the extracted speech, sends a request to the server. However, when the user remains silent, it triggers a no-speech error
My attempt to stop and restart the recognition process resulted in an error message: Uncaught DOMException: Failed to execute 'start' on 'SpeechRecognition': recognition has already started.
How can I configure the system to continue listening until at least some speech is successfully extracted?
Code:
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.continuous = true;
function startRecognition() {
recognition.onresult = async (event) => {
const transcript = event.results[0][0].transcript;
const intent = await extractIntent(transcript);
console.log('Recognized speech:', transcript);
console.log('Recognized intent:', intent);
const payload = {
...
}
await fetch(awsUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
};
// Event listener for errors
recognition.onerror = (event) => {
console.error('Speech recognition error:', event.error);
recognition.stop();
startRecognition();
};
recognition.onnomatch = () => {
console.log("Speech not recognized, trying again...");
recognition.stop();
startRecognition();
};
// Start recognition after everything is set up
console.log('Listening...');
recognition.start();
}