DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at cassidoo.co on

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:

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 <audio> tag to showcase the preview of your recorded audio, and voilà, you are all set.

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.

Top comments (0)