react audio recorder code example
Example 1: react record voice
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: react audio player
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import ReactAudioPlayer from '../src/index.tsx';
describe('ReactAudioPlayer', function() {
const song = './fixtures/turkish_march.ogg';
test('renders an audio element', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer />
);
const instanceEl = ReactDOM.findDOMNode(instance);
expect(instanceEl.tagName).toBe('AUDIO');
});
test('sets the loop attribute if provided', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer
src={song}
loop
/>
);
const instanceEl = ReactDOM.findDOMNode(instance);
expect(instanceEl.getAttribute('loop')).not.toBe(null);
})
test('sets title', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer
src={song}
title="Turkish march"
/>
);
const instanceEl = ReactDOM.findDOMNode(instance);
expect(instanceEl.getAttribute("title")).toBe("Turkish march");
})
test('receives all custom props', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer
src={song}
name="custom-name"
data-id="custom-data"
controlsList="nodownload"
/>
);
const props = Object.keys(instance.props);
expect(props).toContain('name');
expect(props).toContain('data-id');
expect(props).toContain('controlsList');
});
});