I am building a registration form in React where users can input their username and record audio using the react-audio-voice-recorder library. I am using the useState
hook to manage the state of the recorded audio blob, but it's returning null when I try to access it in the handleSubmit
function.
Here's a simplified version of my code:
import React, { useState } from 'react';
import { Button, TextField, Typography } from '@mui/material';
import { AudioRecorder } from 'react-audio-voice-recorder';
const Register = () => {
const [username, setUsername] = useState('');
const [recordedAudio, setRecordedAudio] = useState(null);
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handleRecordingComplete = (blob) => {
console.log("Recording completed:", blob);
setRecordedAudio(blob);
};
const handleSubmit = () => {
if (!username || !recordedAudio) {
alert('Please enter a username and record audio before submitting.');
return;
}
console.log(`Username: ${username}`);
console.log(`Recorded Audio Blob:`, recordedAudio);
// Code to submit username and recorded audio for registration
setUsername('');
setRecordedAudio(null);
};
return (
<div>
<Typography variant="h4" gutterBottom>
Register
</Typography>
<TextField
label="Username"
variant="outlined"
value={username}
onChange={handleUsernameChange}
fullWidth
margin="normal"
/>
<AudioRecorder
onRecordingComplete={handleRecordingComplete}
audioTrackConstraints={{
noiseSuppression: true,
echoCancellation: true,
}}
onNotAllowedOrFound={(err) => console.error(err)}
downloadOnSavePress={false}
showVisualizer={true}
/>
<Button variant="contained" color="primary" onClick={handleSubmit}>
Submit
</Button>
</div>
);
};
export default Register;
When I try to access recordedAudio
in the handleSubmit
function, it returns null. Is there something I'm missing or doing wrong in managing the state of the recorded audio blob?
Any insights or suggestions would be greatly appreciated. Thank you!
It can be done as this:
import React, { useRef, useState } from "react";
const Register = () => {
const mediaRecorderRef = useRef(null);
const [recordedBlob, setRecordedBlob] = useState(null);
const [isRecording, setIsRecording] = useState(false);
const navigate = useNavigate();
const startRecording = async () => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
mediaRecorderRef.current = mediaRecorder;
const chunks = [];
mediaRecorder.ondataavailable = (e) => chunks.push(e.data);
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, { type: "audio/webm" });
setRecordedBlob(blob);
setIsRecording(false);
};
mediaRecorder.start();
setIsRecording(true);
};
const stopRecording = () => {
if (mediaRecorderRef.current && mediaRecorderRef.current.state === "recording") {
mediaRecorderRef.current.stop();
}
};
const toggleRecording = () => {
if (isRecording) {
stopRecording();
} else {
startRecording();
}
};