Skip to content

useMicrophone

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

useMicrophone

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.

Usage Examples

Basic

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>
  );
}

Advanced (Recording)

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>
  );
}

API Reference

Parameters

  • 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 } }.

Return Object

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 between 0 and 100.
  • isRecording (boolean): True if the internal MediaRecorder is currently capturing data.
  • recordedAudioBlob (Blob | null): The final binary audio file after recording stops.
  • recordedAudioUrl (string | null): A locally generated blob: 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. Returns true if successful.
  • stopRecording (() => void): Stops capturing and generates the Blob and URL.
  • clearRecording (() => void): Deletes the stored recording and safely revokes the blob URL to prevent memory leaks.

Core Working

  1. Hardware Access: When requestMicrophone is called, it triggers navigator.mediaDevices.getUserMedia(constraints).
  2. Audio Analysis: Once granted, the stream is fed into the Web Audio API (AudioContext and AnalyserNode). A recursive requestAnimationFrame loop calculates the Fast Fourier Transform (FFT) byte data to calculate the average volume.
  3. Throttled Rendering: To prevent disastrous React performance, the FFT loop throttles state updates via a performance.now() check, limiting audioLevel updates to a maximum of 10 times per second (100ms throttle).
  4. Memory Management: When stopMicrophone is called, all hardware tracks are strictly terminated (track.stop()), the AudioContext is closed, and any dangling animation frames are cancelled. Blob URLs are actively revoked via URL.revokeObjectURL() to prevent nasty memory leaks.

Clone this wiki locally