36
loading...
This website collects cookies to deliver better user experience
<InputGroup.Append>
<img
src='https://img.icons8.com/dusk/64/000000/microphone.png'
alt='microphone-icon'
variant='info'
type="submit"
className="mb-2 voice-chat-btn"
onClick={() => handleVoice(recognition)}
/>
</InputGroup.Append>
handleVoice()
that got executed whenever the user clicks on the microphone. The idea is, when the user clicks on that button, our bot will automatically knows to listen for the human voice and translate it from voice to text. First, let's initialize our speech recognition using Web Speech API:const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
const recognition = new SpeechRecognition();
recognition.lang = 'en-US';
handleVoice()
function that will translate our voice-to-text:const handleVoice = (recognition) => {
recognition.start()
recognition.onresult = function (event) {
const resultIndx = event.resultIndex
const transcript = event.results[resultIndx][0].transcript
setUserHistory([transcript, ...userHistory])
matchReply(transcript)
}
}
const speak = (string) => {
const u = new SpeechSynthesisUtterance();
const allVoices = speechSynthesis.getVoices();
u.voice = allVoices.filter(voice => voice.name === "Alex")[0];
u.text = string;
u.lang = "en-US";
u.volume = 1;
u.rate = 1;
u.pitch = 1;
speechSynthesis.speak(u);
}
matchReply()
, let's execute our newly added speak()
function:const matchReply = (userInput) => {
...
setBotHistory([botMsg, ...botHistory])
speak(botMsg)
}