The goal is to receive audio from the users microphone to and store that audio on a database. To do this, we first need to ask the user, in their browser if we can use their microphone.
const [trackOne, setTrackOne] = useState( { isRecording: false, blobURL: '', isBlocked: false, }) // one time check for mic permissions useEffect(() => { navigator.getUserMedia({ audio: true }, () => { console.log('Permission Granted'); setTrackOne({ isBlocked: false }); }, () => { console.log('Permission Denied'); setTrackOne({ isBlocked: true }) }, ); }, [])
Once permission is granted, a function can be called to start the recording.
const startOne = (e) => { if (trackOne.isBlocked) { console.log('Permission Denied'); } else { Mp3Recorder .start() .then(() => { setTrackOne({ isRecording: true }); }).catch((e) => console.error(e)); } };
In order to stop the recording a function must be called that stops the recording.
const stopOne = () => { Mp3Recorder .stop() .getMp3() .then(([buffer, blob]) => { const file = new File(buffer, 'track-one.mp3', { type: audioType }) setAudioData(file) const blobURL = URL.createObjectURL(blob) setTrackOne({ blobURL, isRecording: false }) }) }
Then a useEffect can be used to post the data whenever the stop button is clicked.
const formData = new FormData() formData.append('audio_data', audioData) useEffect(()=>{ fetch('/tracks', { method: 'POST', body: formData, }) .then((r) => { if (r.ok) { fetch('/tracks') .then(r => r.json()) .then(data => setAllTracks(data)) } }) }, [audioData])
The included fetch GET request at the end is to immediately render the new track.
libraries involved:
import MicRecorder from 'mic-recorder-to-mp3';
important
A bit rate must be set in your audio recording component
const Mp3Recorder = new MicRecorder({ bitRate: 128 });
Top comments (0)