I am trying to add speech recognition to my web application. I am using Web Api's speech recognition. This is my react's code:
import logo from './logo.svg';
import './App.css';
import React from 'react';
import { Typography, Button, Box } from '@mui/material';
function App() {
const [values,setValues] = React.useState("Click on the start button and start speaking.");
var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition = new SpeechRecognition();
recognition.continuous = true;
recognition.lang = 'en-US';
recognition.interimResults = true;
recognition.onresult = function(event) {
console.log("Value is "+event.results[0][0].transcript)
setValues(event.results[0][0].transcript)
}
return (
<React.Fragment>
<Typography align='center' variant="h1">
Filler word helper
</Typography>
<Box sx={{
backgroundColor:'gray',
maxWidth:'md',
margin:'auto',
minHeight:200,
}}>
<Typography style={{
paddingLeft:'2%',
paddingRight:'2%'
}} color="white">
{values}
</Typography>
</Box>
<Box sx={{
display:'flex',
justifyContent:'space-around',
paddingTop:'2%'
}}>
<Button
onClick={()=>{
recognition.start()
}}
variant="contained"
>Start</Button>
<Button
onClick={()=>{
setValues("Click on the start button and start speaking.")
}}
variant="contained"
>Clear</Button>
<Button
onClick={()=>{
recognition.abort()
recognition.stop()
console.log("Stop pressed")
}}
variant="contained"
>Stop</Button>
</Box>
</React.Fragment>
);
}
export default App;
The problem is that after I start the process I cannot stop it. It keeps on going. I did try stopping and aborting and trying various combinations.
Can anyone help me with this issue ?
The issue seems to be that you have set continuous to true.
This appears to always listen to the user, even when it has been aborted.
To fix this, you simply have to set it to false, as below.
recognition.continuous = false;
Also, by default, continuous is set to false, so removing it will have the same result.
This should stop the SpeechRecognition API from listening continuously, and abort/stop when abort() and stop() are called.