1import React, { useState, useEffect } from 'react';
2// the button form material-ui is optional
3// npm install @material-ui/core
4import Button from '@material-ui/core/Button';
5
6const SpeechRecognition =
7 window.SpeechRecognition || window.webkitSpeechRecognition
8const mic = new SpeechRecognition()
9
10mic.continuous = true
11mic.interimResults = true
12mic.lang = 'en-US'
13
14const RecordButton = () => {
15
16 const [isMicOn, setIsMicOn] = useState(false);
17
18 var buttonColour;
19 var buttonLabel;
20
21 if (isMicOn) {
22 buttonColour = "secondary";
23 buttonLabel = "Recording...";
24 } else {
25 buttonColour = "primary";
26 buttonLabel = "Record";
27 }
28
29 useEffect(() => {
30 handleListen()
31 }, [isMicOn])
32
33 const handleListen = () => {
34 if (isMicOn) {
35 mic.start()
36 mic.onend = () => {
37 console.log('continue..')
38 mic.start()
39 }
40 } else {
41 mic.stop()
42 mic.onend = () => {
43 console.log('Stopped Mic on Click')
44 }
45 }
46 mic.onstart = () => {
47 console.log('Mics on')
48 }
49
50 mic.onresult = event => {
51 const transcript = Array.from(event.results)
52 .map(result => result[0])
53 .map(result => result.transcript)
54 .join('')
55 console.log(transcript)
56 mic.onerror = event => {
57 console.log(event.error)
58 }
59 }
60 }
61 // if you don't want to us the button from Material-ui, just change Button to button
62 return(
63 <Button variant="contained" color={buttonColour} onClick={() => {setIsMicOn(!isMicOn)}} >{buttonLabel}</Button>
64 )
65}
66
67export default RecordButton;