react record audio code example
Example 1: React microphone
import React, { useState, useEffect } from 'react';
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)
}
}
}
return(
<Button variant="contained" color={buttonColour} onClick={() => {setIsMicOn(!isMicOn)}} >{buttonLabel}</Button>
)
}
export default RecordButton;
Example 2: play sound onload react
class Music extends React.Component {
state = {
play: false
}
audio = new Audio(this.props.url)
componentDidMount() {
audio.addEventListener('ended', () => this.setState({ play: false }));
}
componentWillUnmount() {
audio.removeEventListener('ended', () => this.setState({ play: false }));
}
togglePlay = () => {
this.setState({ play: !this.state.play }, () => {
this.state.play ? this.audio.play() : this.audio.pause();
});
}
render() {
return (
<div>
<button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
</div>
);
}
}
export default Music;
Example 3: react-sound example
jsimport useSound from 'use-sound';import useSound from 'use-sound';
.npm__react-simple-code-editor__textarea:empty {
-webkit-text-fill-color: inherit !important;
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.npm__react-simple-code-editor__textarea {
color: transparent !important;
}
.npm__react-simple-code-editor__textarea::selection {
background-color: #accef7 !important;
color: transparent !important;
}
}