React microphone

import React, { useState, useEffect } from 'react';
// the button form material-ui is optional
// npm install @material-ui/core
import Button from '@material-ui/core/Button';

const SpeechRecognition =
  window.SpeechRecognition || window.webkitSpeechRecognition
const mic = new SpeechRecognition()

mic.continuous = true
mic.interimResults = true
mic.lang = 'en-US'

const RecordButton = () => {

    const [isMicOn, setIsMicOn] = useState(false);

    var buttonColour;
    var buttonLabel;

    if (isMicOn) {
        buttonColour = "secondary";
        buttonLabel = "Recording...";
    } else {
        buttonColour = "primary";
        buttonLabel = "Record";
    }

    useEffect(() => {
        handleListen()
      }, [isMicOn])
    
    const handleListen = () => {
    if (isMicOn) {
        mic.start()
        mic.onend = () => {
        console.log('continue..')
        mic.start()
        }
    } else {
        mic.stop()
        mic.onend = () => {
        console.log('Stopped Mic on Click')
        }
    }
    mic.onstart = () => {
        console.log('Mics on')
    }
    
    mic.onresult = event => {
        const transcript = Array.from(event.results)
        .map(result => result[0])
        .map(result => result.transcript)
        .join('')
        console.log(transcript)
        mic.onerror = event => {
        console.log(event.error)
          }
        }
      }
	// if you don't want to us the button from Material-ui, just change Button to button
    return(
        <Button variant="contained" color={buttonColour} onClick={() => {setIsMicOn(!isMicOn)}} >{buttonLabel}</Button>
    )
}

export default RecordButton;

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source