-
Notifications
You must be signed in to change notification settings - Fork 0
useMicrophone
Saurav-TB-Pandey edited this page Aug 10, 2026
·
2 revisions
A powerful hook that handles the complete lifecycle of the browser's Microphone. It requests permissions, captures the MediaStream, provides a real-time audio volume level (throttled to 10 FPS for maximum performance), and allows you to record the audio straight into an MP4/WebM blob.
Requesting access to the microphone and displaying a live volume meter.
import { useMicrophone } from "react-hook-lab";
function AudioMonitor() {
const { status, audioLevel, requestMicrophone, stopMicrophone } = useMicrophone();
if (status !== "granted") {
return <button onClick={requestMicrophone}>Enable Microphone</button>;
}
return (
<div>
<p>Live Volume: {audioLevel}%</p>
{/* A simple visual volume bar */}
<div style={{ width: `${audioLevel}%`, height: '20px', background: 'green' }} />
<button onClick={stopMicrophone}>Turn Off Mic</button>
</div>
);
}Using the built-in MediaRecorder engine to capture audio, save it, and play it back in the browser.
import { useMicrophone } from "react-hook-lab";
function VoiceRecorder() {
const {
status, requestMicrophone,
isRecording, startRecording, stopRecording,
recordedAudioUrl, clearRecording
} = useMicrophone();
return (
<div>
{status !== "granted" && (
<button onClick={requestMicrophone}>Start Microphone</button>
)}
{status === "granted" && !isRecording && (
<button onClick={startRecording}>Start Recording</button>
)}
{isRecording && (
<button onClick={stopRecording} className="stop-btn">
Stop Recording
</button>
)}
{recordedAudioUrl && (
<div>
<h3>Playback</h3>
<audio src={recordedAudioUrl} controls />
<button onClick={clearRecording}>Trash Recording</button>
</div>
)}
</div>
);
}-
constraints(Optional)- Type:
MediaStreamConstraints - Default:
{ audio: true } - Description: The constraints to apply when requesting the hardware. You can pass advanced config like
{ audio: { echoCancellation: true, noiseSuppression: true } }.
- Type:
Returns an object of type UseMicrophoneReturn containing:
-
stream(MediaStream | null): The raw hardware stream. -
status(MicrophoneStatus): The current hardware state ("idle" | "unsupported" | "prompting" | "granted" | "denied" | "error"). -
error(string | null): A human-readable error message. -
audioLevel(number): The real-time volume level, strictly clamped between0and100. -
isRecording(boolean): True if the internalMediaRecorderis currently capturing data. -
recordedAudioBlob(Blob | null): The final binary audio file after recording stops. -
recordedAudioUrl(string | null): A locally generatedblob:URL that can be directly passed to<audio src={...} />. -
requestMicrophone(() => Promise<void>): Initiates the browser permission prompt and hardware startup. -
stopMicrophone(() => void): Completely shuts down the hardware, stopping the green recording indicator in the user's browser tab. -
startRecording(() => boolean): Begins capturing the audio to a file. Returnstrueif successful. -
stopRecording(() => void): Stops capturing and generates theBlobandURL. -
clearRecording(() => void): Deletes the stored recording and safely revokes the blob URL to prevent memory leaks.
-
Hardware Access: When
requestMicrophoneis called, it triggersnavigator.mediaDevices.getUserMedia(constraints). -
Audio Analysis: Once granted, the stream is fed into the Web Audio API (
AudioContextandAnalyserNode). A recursiverequestAnimationFrameloop calculates the Fast Fourier Transform (FFT) byte data to calculate the average volume. -
Throttled Rendering: To prevent disastrous React performance, the FFT loop throttles state updates via a
performance.now()check, limitingaudioLevelupdates to a maximum of 10 times per second (100ms throttle). -
Memory Management: When
stopMicrophoneis called, all hardware tracks are strictly terminated (track.stop()), theAudioContextis closed, and any dangling animation frames are cancelled.BlobURLs are actively revoked viaURL.revokeObjectURL()to prevent nasty memory leaks.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM