"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Making a simple React microphone component

Making a simple React microphone component

Published on 2024-10-31
Browse:802

Making a simple React microphone component

More than once lately I’ve had to make some kind of React microphone component that records audio in the browser, and then you do whatever you want with the audio blob you get there (store it, transform it, use it with a transcription library, whatever).

The components out there in the wild for React microphones are… unmaintained. I’ll generally leave it at that. They’re not bad, necessarily, but some of the repositories lead to spam, some are full of broken links, and most of them that I could find haven’t been updated in more than a few years.

If you want something done, you have to do it yourself

I decided to make one of these components from scratch!

Here is a link to the 125-line gist if you just want to use it and not have to read the rest of this blog post. So impatient. But I understand. Life is challenging.

Anyway.

There’s a bunch of things you generally have to account for with microphones. I didn’t go deep into browser compatibility with this one (I’m sure like… Opera or something would probably have trouble with this), but there are some nice built-in modern browser features that’ll get you pretty far, here:

  • navigator.mediaDevices: this lets you access the user’s microphone (or camera, if you want that)
  • getUserMedia: this lets you get user permission for the aforementioned media devices, and produces a media stream.
  • MediaRecorder: this lets you actually record things

All of these combined with some React state variables for tracking each of them, a useEffect for doing browser-side things, and then a native

It’s all easier said than done, of course, so that’s why I put it all in a copy-and-pasteable gist. Outside of the base functionality, I also made a variable for a maximum recording time (you don’t need it, but if you want to transcribe something or upload something, I figure limits are good), and some small Tailwind styles to show some animations around the button.

Use the component. Record your dreams.

Release Statement This article is reproduced at: https://dev.to/cassidoo/making-a-simple-react-microphone-component-2pbo?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3