Home > Web Front-end > JS Tutorial > Making a simple React microphone component

Making a simple React microphone component

WBOY
Release: 2024-08-28 06:06:35
Original
855 people have browsed it

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.

The above is the detailed content of Making a simple React microphone component. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template