### Install react-audio-wavekit Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/README.md Install the library using npm, pnpm, or bun. Ensure you have React 18+ and the Web Audio API / MediaRecorder API available. ```bash npm install react-audio-wavekit # or pnpm add react-audio-wavekit # or bun add react-audio-wavekit ``` -------------------------------- ### Complete Usage Example with Recording Controls Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/live-streaming-stack-recorder.md Demonstrates a full implementation of the LiveStreamingStackRecorder component integrated with audio recording controls. This example shows how to start, stop, pause, and resume recording, and displays the waveform visualization with custom appearance settings. ```typescript import { LiveStreamingStackRecorder, useAudioRecorder } from "react-audio-wavekit"; import { useState } from "react"; export function StackRecorderExample() { const { startRecording, stopRecording, pauseRecording, resumeRecording, mediaRecorder, isRecording, isPaused, recordingBlob, recordingTime, } = useAudioRecorder(); const [recording, setRecording] = useState(false); const handleStart = async () => { await startRecording(); setRecording(true); }; const handleStop = () => { stopRecording(); setRecording(false); }; return (
{recording && ( <> )}
{/* Fixed-width waveform - bars compress as recording grows */} {recording && (
Recording: {recordingTime}s
)} {recordingBlob && (
✓ Saved: {(recordingBlob.size / 1024).toFixed(1)} KB
)}
); } ``` -------------------------------- ### Complete Audio Recording Workflow Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md This example demonstrates a full audio recording workflow using the useAudioRecorder hook, including UI controls for starting, pausing, resuming, and stopping recordings, as well as handling saved blobs and download functionality. It configures MIME type and audio constraints. ```typescript import { useAudioRecorder } from "react-audio-wavekit"; import { useRef, useState } from "react"; export function AudioRecorderApp() { const [savedBlob, setSavedBlob] = useState(null); const { startRecording, stopRecording, pauseRecording, resumeRecording, mediaRecorder, recordingBlob, recordingTime, isRecording, isPaused, error, } = useAudioRecorder({ mimeType: "audio/webm", audioConstraints: { echoCancellation: true, noiseSuppression: true, autoGainControl: false, }, onRecordingComplete: (blob) => { setSavedBlob(blob); console.log("Recording saved:", blob.size, "bytes"); }, }); const handleStart = async () => { try { await startRecording(); } catch (err) { console.error("Failed to start recording:", err); } }; const handleStop = () => { stopRecording(); }; const handleDownload = () => { if (!recordingBlob) return; const url = URL.createObjectURL(recordingBlob); const a = document.createElement("a"); a.href = url; a.download = `recording-${Date.now()}.webm`; a.click(); URL.revokeObjectURL(url); }; if (error) { return
Error: {error.message}
; } return (
{isRecording && ( <> )}
{isRecording && (
{recordingTime}s {isPaused && "(paused)"}
)} {savedBlob && (
✓ Recording ready ({(savedBlob.size / 1024).toFixed(1)} KB)
)}
); } ``` -------------------------------- ### Complete Live Streaming Recorder Usage Example Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/live-streaming-recorder.md This example demonstrates how to use the LiveStreamingRecorder with controls for starting, stopping, pausing, and resuming recordings. It includes a visual waveform display and shows the recording status. ```typescript import { LiveStreamingRecorder, useAudioRecorder } from "react-audio-wavekit"; import { useState } from "react"; export function RecorderWithScrolling() { const { startRecording, stopRecording, pauseRecording, resumeRecording, mediaRecorder, isRecording, isPaused, recordingBlob, } = useAudioRecorder(); const [recording, setRecording] = useState(false); const handleStart = async () => { await startRecording(); setRecording(true); }; const handleStop = () => { stopRecording(); setRecording(false); }; const handlePauseResume = () => { if (isPaused) { resumeRecording(); } else { pauseRecording(); } }; return (
{recording && ( <> )}
{/* Scrolling timeline waveform */} {recordingBlob && (
✓ Recording complete ({(recordingBlob.size / 1024).toFixed(2)} KB)
)}
); } ``` -------------------------------- ### Start Development Watch Mode Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Starts the development server in watch mode for live code updates. ```bash bun run dev ``` -------------------------------- ### Start Storybook for Visual Testing Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Launches Storybook to visually test and develop components in isolation. ```bash bun run storybook ``` -------------------------------- ### Example: Audio Waveform Appearance Configuration Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/types.md Configure both general waveform styling and specific playhead styling. ```typescript const appearance: AudioWaveformAppearance = { barColor: "#3b82f6", barWidth: 2, barGap: 1, barRadius: 1, barHeightScale: 0.95, playheadColor: "#ef4444", playheadWidth: 2, }; ``` -------------------------------- ### React Audio Player Integration with AudioWaveform Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/audio-waveform.md This example demonstrates a complete integration of the AudioWaveform component with a custom audio player. It handles loading audio, syncing playback time, and seeking functionality. Ensure you have an audio file (e.g., 'audio.mp3') accessible at the root for this example to work. ```typescript import { AudioWaveform } from "react-audio-wavekit"; import { useState, useRef, useEffect } from "react"; export function AudioPlayer() { const [blob, setBlob] = useState(null); const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0); const audioRef = useRef(null); // Load audio file useEffect(() => { fetch("/audio.mp3") .then(res => res.blob()) .then(blob => { setBlob(blob); const url = URL.createObjectURL(blob); if (audioRef.current) audioRef.current.src = url; }); }, []); // Sync audio element time with waveform useEffect(() => { const audio = audioRef.current; if (!audio) return; const handleTimeUpdate = () => setCurrentTime(audio.currentTime); const handleLoadedMetadata = () => setDuration(audio.duration); audio.addEventListener("timeupdate", handleTimeUpdate); audio.addEventListener("loadedmetadata", handleLoadedMetadata); return () => { audio.removeEventListener("timeupdate", handleTimeUpdate); audio.removeEventListener("loadedmetadata", handleLoadedMetadata); }; }, []); return (
audioRef.current?.pause()} onSeekDrag={(time) => setCurrentTime(time)} onSeekEnd={(time) => { if (audioRef.current) { audioRef.current.currentTime = time; audioRef.current.play(); } }} className="w-full h-40 bg-slate-100 rounded-lg p-4" appearance={{ barColor: "#3b82f6", barWidth: 2, barGap: 1, barRadius: 1, playheadColor: "#ef4444", playheadWidth: 2, }} />
); } ``` -------------------------------- ### Web Audio API Setup with useAudioAnalyser Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/ADVANCED.md Use this hook for real-time audio analysis. It manages Web Audio API setup, including AudioContext and AnalyserNode, and connects to a MediaRecorder stream. It's useful for building custom visualization components. ```typescript function useAudioAnalyser(config: UseAudioAnalyserConfig): UseAudioAnalyserReturn ``` ```typescript interface UseAudioAnalyserConfig { mediaRecorder: MediaRecorder | null; fftSize?: number; // Default: 2048 smoothingTimeConstant?: number; // Default: 0.8 } ``` ```typescript interface UseAudioAnalyserReturn { audioContextRef: React.MutableRefObject; analyserRef: React.MutableRefObject; dataArrayRef: React.MutableRefObject | null>; bufferLengthRef: React.MutableRefObject; } ``` -------------------------------- ### Complete LiveRecorder Usage Example Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/live-recorder.md An example demonstrating how to use the LiveRecorder component with the useAudioRecorder hook for real-time audio visualization during recording. It includes controls to start/stop recording and access the analyser node. ```typescript import { LiveRecorder, useAudioRecorder } from "react-audio-wavekit"; import { useRef, useState } from "react"; export function LiveRecorderExample() { const { startRecording, stopRecording, mediaRecorder, isRecording, recordingBlob } = useAudioRecorder(); const recorderRef = useRef(null); const handleStart = async () => { await startRecording(); }; const handleStop = () => { stopRecording(); }; const handleAnalyserAccess = () => { const analyser = recorderRef.current?.getAnalyser(); if (analyser) { console.log("Frequency bins:", analyser.frequencyBinCount); } }; return (
{/* Real-time frequency visualization */} {recordingBlob && (
Recording saved: {recordingBlob.size} bytes
)}
); } ``` -------------------------------- ### Run Storybook Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Starts the Storybook development server on port 6006 for component demos. Requires Node.js 20.19+ or 22.12+. ```bash bun run storybook # Run Storybook dev server (port 6006) ``` -------------------------------- ### Minimal useAudioRecorder Usage Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/README.md Use this snippet to start recording and access the MediaRecorder instance. ```typescript // Just record const { startRecording, mediaRecorder } = useAudioRecorder(); ``` -------------------------------- ### Record Audio with Live Visualization Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/API-OVERVIEW.md Utilize the useAudioRecorder hook and LiveStreamingRecorder component to capture audio with real-time waveform visualization. This setup allows for starting, stopping, and displaying the recorded audio. ```typescript import { useAudioRecorder, LiveStreamingRecorder } from "react-audio-wavekit"; import { useState } from "react"; function AudioRecorder() { const [saved, setSaved] = useState(null); const { startRecording, stopRecording, mediaRecorder, isRecording } = useAudioRecorder({ onRecordingComplete: setSaved, }); return ( <> {saved &&

Recorded: {saved.size} bytes

} ); } ``` -------------------------------- ### High-Quality Audio Constraints Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md This example configures `audioConstraints` for higher audio quality by enabling echo cancellation, noise suppression, auto-gain control, and specifying a sample size. This setup is ideal for applications requiring enhanced audio fidelity. ```typescript useAudioRecorder({ audioConstraints: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, sampleSize: 16, } }) // Enhanced audio quality with processing ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/next-test/README.md Use these commands to start the local development server for your Next.js project. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Project Development and Quality Assurance Commands Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/GEMINI.md Bun commands for starting the development server, running Storybook, linting, fixing issues, and running tests. ```bash # Development bun run dev # Start Vite in watch mode bun run storybook # Start Storybook server (port 6006) # Quality Assurance bun run check # Lint & type-check (Biome + tsgo) bun run fix # Auto-fix linting issues bun run test # Run unit tests (Vitest) # Build bun run build # Build library to dist/ (ESM, CJS, .d.ts) bun run build-storybook # Build static Storybook site ``` -------------------------------- ### Example: Waveform Appearance Configuration Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/types.md Set specific values for waveform bar styling properties. ```typescript const appearance: WaveformAppearance = { barColor: "#3b82f6", barWidth: 2, barGap: 1, barRadius: 1, barHeightScale: 0.95, }; ``` -------------------------------- ### Simple Click-to-Seek Example Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/audio-waveform.md Implement simple click-to-seek functionality by providing an onSeek callback. This is suitable when real-time feedback during dragging is not required. ```typescript audio.currentTime = time} /> ``` -------------------------------- ### Example: Live Streaming Recorder Appearance Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/types.md Configure both waveform and scrollbar styles for a live streaming recorder. ```typescript const appearance: LiveStreamingRecorderAppearance = { barColor: "#3b82f6", barWidth: 2, barGap: 1, barRadius: 1, barHeightScale: 0.95, scrollbar: { thumbColor: "rgba(148, 163, 184, 0.6)", hidden: false, }, }; ``` -------------------------------- ### Start and Stop Recording with Timeline Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Use this snippet to initiate and halt audio recording, integrating with a live streaming canvas for visualization. ```typescript const { startRecording, mediaRecorder, isRecording } = useAudioRecorder(); <> ``` -------------------------------- ### Example: Scrollbar Appearance Configuration Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/types.md Set custom color and visibility for the scrollbar thumb. ```typescript const appearance = { scrollbar: { thumbColor: "rgba(59, 130, 246, 0.6)", hidden: false, }, }; ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/CLAUDE.md Commands to start watch mode, run Storybook for visual testing, auto-fix linting, and verify types and linting during development. ```bash bun run dev # Start watch mode bun run storybook # Visual testing # Make changes... bun run fix # Auto-fix linting bun run check # Verify types + lint ``` -------------------------------- ### File Naming Convention Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/CLAUDE.md Specifies the kebab-case naming convention for files within the project, providing an example. ```plaintext File naming: kebab-case (e.g., audio-waveform.tsx, use-audio-recorder.ts) ``` -------------------------------- ### Full Featured AudioWaveform Usage Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Example of using the AudioWaveform component with various props for customization and interaction. ```typescript ``` -------------------------------- ### Example Usage of useAudioRecorder Hook Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/types.md Demonstrates how to use the useAudioRecorder hook in a React component to display recording status and time. ```typescript import type { UseAudioRecorderReturn } from "react-audio-wavekit"; function RecorderComponent() { const recorder: UseAudioRecorderReturn = useAudioRecorder(); return (
{recorder.isRecording && (

Recording: {recorder.recordingTime}s

)}
); } ``` -------------------------------- ### Drag-to-Seek with Pause/Resume Example Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/audio-waveform.md Enable drag-to-seek with pause and resume functionality for seamless seeking. This involves using onSeekStart, onSeekDrag, and onSeekEnd callbacks to manage audio playback state. ```typescript audio.pause()} onSeekDrag={(time) => setCurrentTime(time)} onSeekEnd={(time) => { audio.currentTime = time; audio.play(); }} /> ``` -------------------------------- ### Fixed MIME Type Configuration Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md This example demonstrates how to explicitly set a single MIME type for audio recording using the `mimeType` option. Be aware that specifying a fixed type might lead to failures on browsers that do not support it, such as Safari with 'audio/webm'. ```typescript const { mediaRecorder } = useAudioRecorder({ mimeType: "audio/webm" }); // Always uses audio/webm, may fail on Safari ``` -------------------------------- ### Record Audio with Live Timeline Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/README.md Utilize the useAudioRecorder hook and the LiveStreamingRecorder component to record audio and visualize it in real-time. Start recording by calling the startRecording function. ```typescript import { useAudioRecorder, LiveStreamingRecorder } from "react-audio-wavekit"; function Recorder() { const { startRecording, mediaRecorder, isRecording } = useAudioRecorder(); return ( <> ); } ``` -------------------------------- ### Handle Recording Errors Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Implement error handling for the start recording function to catch and log potential issues like permission denials. ```typescript const { error, startRecording } = useAudioRecorder(); const handleStart = async () => { try { await startRecording(); } catch (err) { console.error("Permission denied:", err); } }; {error &&
{error.message}
} ``` -------------------------------- ### Full Audio Editor (Record + Playback) Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/API-OVERVIEW.md Combine recording and playback functionalities into a single audio editor component. This example demonstrates switching between record and playback modes, utilizing both LiveStreamingStackRecorder and AudioWaveform. ```typescript import { AudioWaveform, LiveStreamingStackRecorder, useAudioRecorder, } from "react-audio-wavekit"; import { useRef, useState } from "react"; function AudioEditor() { const audioRef = useRef(null); const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0); const [mode, setMode] = useState<"record" | "playback">("record"); const [recordedBlob, setRecordedBlob] = useState(null); const { startRecording, stopRecording, mediaRecorder, isRecording, recordingBlob, } = useAudioRecorder({ onRecordingComplete: setRecordedBlob }); const playingBlob = mode === "playback" ? recordedBlob : null; return (
{mode === "record" && ( <> )} {mode === "playback" && playingBlob && ( <> audioRef.current?.pause()} onSeekDrag={(time) => setCurrentTime(time)} onSeekEnd={(time) => { audioRef.current!.currentTime = time; audioRef.current?.play(); }} />
); } ``` -------------------------------- ### Use Audio Recorder Hook with Recording Complete Callback Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/configuration.md Handles the recorded audio blob upon completion of recording. Includes examples for uploading to a server and saving to local storage. ```typescript useAudioRecorder({ onRecordingComplete: (blob) => { console.log("Recording finished:", blob.size, "bytes"); console.log("MIME type:", blob.type); // Upload to server const formData = new FormData(); formData.append("audio", blob); fetch("/api/upload", { method: "POST", body: formData }); // Save to localStorage const reader = new FileReader(); reader.onloadend = () => { localStorage.setItem("lastRecording", reader.result); }; reader.readAsDataURL(blob); } }) ``` -------------------------------- ### Default Audio Constraints Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md This example shows the default behavior of `audioConstraints` when using `useAudioRecorder`. Setting it to `true` utilizes the browser's default microphone settings, which are generally suitable for most applications. ```typescript useAudioRecorder({ audioConstraints: true }) // Uses browser defaults, usually good for most cases ``` -------------------------------- ### Import Default Appearance Values Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/configuration.md Import and utilize default appearance configurations for waveforms, playheads, and scrollbars. These provide starting points for custom styling. ```typescript import { DEFAULT_WAVEFORM_APPEARANCE, DEFAULT_PLAYHEAD_APPEARANCE, DEFAULT_SCROLLBAR_APPEARANCE, } from "react-audio-wavekit"; // WaveformAppearance defaults DEFAULT_WAVEFORM_APPEARANCE = { barColor: "#3b82f6", // Tailwind blue-500 barWidth: 1, barGap: 1, barRadius: 0, barHeightScale: 0.95, } // AudioWaveformAppearance additional defaults DEFAULT_PLAYHEAD_APPEARANCE = { playheadColor: "#ef4444", // Tailwind red-500 playheadWidth: 2, } // ScrollbarAppearance defaults DEFAULT_SCROLLBAR_APPEARANCE = { thumbColor: "rgba(148, 163, 184, 0.5)", // Tailwind slate-400 at 50% opacity hidden: false, } ``` -------------------------------- ### Mocking AudioContext for Unit Tests Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/ADVANCED.md Provides a Jest mocking example for `AudioContext` to facilitate unit testing of audio-related functionalities. This allows testing without requiring a real browser audio environment. ```typescript // Jest mocking example global.AudioContext = jest.fn(() => ({ createAnalyser: jest.fn(() => ({ getByteTimeDomainData: jest.fn(), fftSize: 2048, })), })); ``` -------------------------------- ### SSR with Suspense Example Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/audio-waveform.md Utilize React Suspense for server-side rendering (SSR) of the AudioWaveform component. This requires a Suspense boundary and ensures audio decoding occurs on the client after mount. ```typescript Loading waveform...}> ``` -------------------------------- ### Library Entry Point Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/API-OVERVIEW.md The react-audio-wavekit library is exported from a single entry point. Tree-shaking is supported, meaning unused components will be removed from the final bundle. ```typescript import { ... } from "react-audio-wavekit"; ``` -------------------------------- ### Build Storybook Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/CLAUDE.md Builds a static site for the Storybook demo. Requires Node.js 20.19+ or 22.12+. ```bash bun run build-storybook ``` -------------------------------- ### Import Core Types Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/types.md Import necessary types for configuring audio waveform appearance and recorder return values. ```typescript import type { AudioWaveformAppearance, WaveformAppearance, ScrollbarAppearance, UseAudioRecorderReturn, } from "react-audio-wavekit"; ``` -------------------------------- ### Handling Recording Errors with useAudioRecorder Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md Demonstrates how to use a try-catch block to handle potential errors during the startRecording process. It also shows how to check the 'error' property returned by the hook after an attempt. ```typescript const { error, startRecording } = useAudioRecorder(); const handleStart = async () => { try { await startRecording(); } catch (err) { // Handle permission denied, browser compatibility, etc. console.error("Recording failed:", err); } }; // Or check error property after attempt if (error) { console.error("Error:", error.message); } ``` -------------------------------- ### Build Storybook Site Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Builds a static version of the Storybook site. Requires Node.js 20.19+ or 22.12+. ```bash bun run build-storybook # Build Storybook static site ``` -------------------------------- ### useAudioRecorder Usage with Full Options Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates advanced configuration of the useAudioRecorder hook, including dynamic mimeType, specific audio constraints, and a recording completion callback. ```typescript const recorder = useAudioRecorder({ mimeType: () => { return /iPhone/.test(navigator.userAgent) ? "audio/mp4" : "audio/webm"; }, audioConstraints: { echoCancellation: true, noiseSuppression: true, }, onRecordingComplete: (blob) => { console.log("Recording saved:", blob.size); }, }); ``` -------------------------------- ### Standard LiveStreamingRecorder Usage Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/README.md Use this snippet to set up a live recording with a scrolling timeline visualization. ```typescript // Record with visualization ``` -------------------------------- ### Build Library Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Builds the library to the dist/ directory, generating ESM, CJS, and .d.ts files. Requires Node.js 20.19+ or 22.12+. ```bash bun run build # Build library to dist/ (ESM, CJS, .d.ts) ``` -------------------------------- ### Build System Configuration Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/CLAUDE.md Configuration details for the build system using Vite 7 library mode with dts plugin. Specifies output formats and external dependencies. ```plaintext Build: Vite 7 library mode with vite-plugin-dts for type generation Styling: Tailwind CSS v4 - classes only, no CSS bundled Output: dist/index.js (ESM), dist/index.cjs (CJS), dist/index.d.ts (types) Externals: React/ReactDOM are peer dependencies, not bundled ``` -------------------------------- ### Library Entry Point Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/CLAUDE.md The main entry point for the library, exporting all public APIs. Uses relative paths for imports. ```typescript src/index.tsx ``` -------------------------------- ### Accessing LiveRecorder Analyser Node Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/live-recorder.md Shows how to get a reference to the LiveRecorder component and access its Web Audio API AnalyserNode after the component has mounted. This allows for custom configuration, such as changing the FFT size. ```typescript const recorderRef = useRef(null); useEffect(() => { const analyser = recorderRef.current?.getAnalyser(); if (analyser) { analyser.fftSize = 4096; // Customize after component mounts } }, []); ``` -------------------------------- ### Development Watch Mode Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Runs the build process in watch mode for development. Requires Node.js 20.19+ or 22.12+. ```bash bun run dev # Watch mode for development ``` -------------------------------- ### LiveStreamingRecorder for Timeline Waveform Recording Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md Use LiveStreamingRecorder for a timeline-style waveform that grows horizontally during recording. It requires a mediaRecorder instance and provides a canvas for visualization. Control recording start, pause, and stop via the useAudioRecorder hook. ```tsx import { LiveStreamingRecorder, useAudioRecorder } from "react-audio-wavekit"; function RecorderExample() { const { startRecording, stopRecording, pauseRecording, resumeRecording, mediaRecorder, isRecording, isPaused } = useAudioRecorder(); const handleRecordClick = () => { if (!isRecording) { startRecording(); } else if (isPaused) { resumeRecording(); } else { pauseRecording(); } }; return (
{/* Record/Pause button */} {/* Timeline waveform - grows horizontally as recording progresses */} {/* Stop button */}
); } ``` -------------------------------- ### AudioWaveform Component Usage Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/audio-waveform.md This snippet demonstrates how to import and use the AudioWaveform component, including its core props for displaying audio waveforms and handling user interactions like seeking. ```APIDOC ## AudioWaveform Component ### Description Provides static waveform visualization with playhead and drag-to-seek support. Visualizes pre-recorded audio files with interactive seeking. ### Props - **blob** (Blob | null) - Optional - Audio file blob to decode and visualize (provide either `blob` or `peaks`). - **peaks** (number[]) - Optional - Pre-computed normalized peak data (0-1 range). Skips decoding when provided. - **appearance** (AudioWaveformAppearance) - Optional - Visual styling for bars and playhead. - **suspense** (boolean) - Optional - Enable React Suspense mode for SSR compatibility. Defaults to `false`. - **currentTime** (number) - Optional - Current playback time in seconds. Required to display playhead position. Use with `duration`. - **duration** (number) - Optional - Total audio duration in seconds. Required for playhead calculation. - **onSeek** ((time: number) => void) - Optional - Simple click-to-seek callback. Fired once on canvas click at calculated time. - **onSeekStart** (() => void) - Optional - Called when user starts drag-to-seek (use to pause playback). - **onSeekDrag** ((time: number) => void) - Optional - Called repeatedly during drag-to-seek with current time. - **onSeekEnd** ((time: number) => void) - Optional - Called when user finishes drag-to-seek. - Standard canvas attributes (`React.CanvasHTMLAttributes`) - Optional - Supports `className`, `style`, `id`, `data-*` attributes, and event handlers (excluding mouse handlers managed internally for seeking). ### Seeking Behavior - **Simple Click-to-Seek**: Use `onSeek` for basic seeking. - **Drag-to-Seek**: Enabled when `onSeekStart`, `onSeekDrag`, or `onSeekEnd` are provided. Use these callbacks to manage playback pause/resume and update the current time during dragging. ### Keyboard Navigation When seek callbacks and duration are provided, the component supports keyboard navigation: - **ArrowLeft**: Seek backward 5 seconds - **ArrowRight**: Seek forward 5 seconds - **Home**: Seek to start (0s) - **End**: Seek to end (duration) ### Ref - **ref** (React.RefObject) - Use to access the underlying canvas element via `ref.current.canvas`. ### SSR Considerations - When `suspense={true}`, the component requires a React Suspense boundary. - Decoding starts after client mount, preventing server-side audio processing. ### Example Usage ```typescript import { AudioWaveform } from "react-audio-wavekit"; function MyWaveform() { const handleSeek = (time: number) => { // Handle seek logic }; return ( ); } ``` ``` -------------------------------- ### useAudioRecorder Hook Usage Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md This snippet demonstrates how to import and use the useAudioRecorder hook, including its configuration options and returned values. ```APIDOC ## useAudioRecorder Hook ### Description Manages the audio recording lifecycle, including setup, stream management, pause/resume, and blob generation. ### Import ```typescript import { useAudioRecorder } from "react-audio-wavekit"; import type { UseAudioRecorderReturn } from "react-audio-wavekit"; ``` ### Signature ```typescript function useAudioRecorder(config?: UseAudioRecorderConfig): UseAudioRecorderReturn ``` ### UseAudioRecorderConfig Configuration object for the hook. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `mimeType` | `string | (() => string)` | No | Auto-select by browser | MIME type for recording. Can be a fixed string or a function for dynamic selection. Defaults to browser auto-detection. | | `audioConstraints` | `MediaTrackConstraints | boolean` | No | `true` | Constraints for `getUserMedia`. `true` uses defaults, an object specifies custom constraints. | | `onRecordingComplete` | `(blob: Blob) => void` | No | — | Callback executed when recording stops and a blob is generated. | ### UseAudioRecorderReturn Methods and state returned by the hook. | Property | Type | Description | |---|---|---| | `startRecording()` | `() => Promise` | Requests microphone access and starts recording. Resets previous state. | | `stopRecording()` | `() => void` | Stops recording, fires `onRecordingComplete`, and releases the stream. | | `pauseRecording()` | `() => void` | Pauses the current recording, preserving state for resumption. | | `resumeRecording()` | `() => void` | Resumes a paused recording. | | `clearRecording()` | `() => void` | Clears recording state and blob. Stops active recording if necessary. | | `mediaRecorder` | `MediaRecorder | null` | The `MediaRecorder` instance. Null if not recording. | | `recordingBlob` | `Blob | null` | The generated audio blob after `stopRecording()`. Null otherwise. | | `recordingTime` | `number` | The duration of the recording in seconds. | | `isRecording` | `boolean` | True if recording is in progress (including paused state). | | `isPaused` | `boolean` | True if the recording is currently paused. | | `error` | `Error | null` | The most recent error encountered. Cleared on successful start. | ``` -------------------------------- ### useAudioRecorder Hook for Recording State Management Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/AGENTS.md The useAudioRecorder hook provides essential state and control functions for managing audio recording. It returns properties like recordingBlob, isRecording, and error, along with methods to start, stop, pause, and resume recording. ```javascript // Returns: { startRecording, stopRecording, pauseRecording, resumeRecording, mediaRecorder, recordingBlob, isRecording, isPaused, recordingTime, error } ``` -------------------------------- ### Custom MIME Type Detection Function Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/use-audio-recorder.md This snippet illustrates how to provide a custom function to the `mimeType` option for more granular control over MIME type selection. The example uses user agent detection to choose between 'audio/mp4' for mobile devices and 'audio/webm' for others. ```typescript const { mediaRecorder } = useAudioRecorder({ mimeType: () => { const isMobile = /iPhone|iPad|Android/.test(navigator.userAgent); return isMobile ? "audio/mp4" : "audio/webm"; }, }); ``` -------------------------------- ### Custom Responsive Styling for LiveStreamingStackRecorder Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/api-reference/live-streaming-stack-recorder.md Applies responsive height classes to adapt the recorder's appearance across different screen sizes, from small to medium breakpoints. The mediaRecorder prop must be supplied. ```typescript ``` -------------------------------- ### Code Quality Workflow Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/CLAUDE.md Outlines the recommended workflow for maintaining code quality: run `bun run fix` after changes, followed by `bun run check` for verification. ```plaintext Code quality: Always run `bun run fix` after code changes, then `bun run check` to verify ``` -------------------------------- ### Common Pattern: Record & Download Audio Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Combines useAudioRecorder with logic to handle downloading the recorded audio blob. ```typescript const { startRecording, stopRecording, recordingBlob } = useAudioRecorder(); const handleDownload = () => { if (!recordingBlob) return; const url = URL.createObjectURL(recordingBlob); const a = document.createElement("a"); a.href = url; a.download = "recording.webm"; a.click(); }; ``` -------------------------------- ### Constants Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/API-OVERVIEW.md Provides default configuration constants for waveform appearance, playhead, and scrollbars, which are rarely needed but available for reference. ```APIDOC ## Constants ### Default Constants - **DEFAULT_WAVEFORM_APPEARANCE**: Default styling for waveforms. - **DEFAULT_PLAYHEAD_APPEARANCE**: Default styling for the playhead. - **DEFAULT_SCROLLBAR_APPEARANCE**: Default styling for scrollbars. ### Import Example ```typescript import { DEFAULT_WAVEFORM_APPEARANCE, DEFAULT_PLAYHEAD_APPEARANCE, DEFAULT_SCROLLBAR_APPEARANCE, } from "react-audio-wavekit"; ``` ``` -------------------------------- ### AudioWaveform Keyboard Navigation Handler Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/ADVANCED.md Implements keyboard event handling for `AudioWaveform` to support seeking functionality. Users can navigate audio playback using arrow keys, Home, and End keys. ```typescript const handleKeyDown = (e: React.KeyboardEvent) => { switch (e.key) { case "ArrowLeft": onSeek(Math.max(0, currentTime - 5)); break; case "ArrowRight": onSeek(Math.min(duration, currentTime + 5)); break; case "Home": onSeek(0); break; case "End": onSeek(duration); break; } }; ``` -------------------------------- ### Appearance Shortcut: Large/Desktop Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Configures a larger waveform appearance suitable for desktop, with thicker bars, gaps, and rounded corners. ```typescript appearance={{ barColor: "#3b82f6", barWidth: 3, barGap: 2, barRadius: 2, }} ``` -------------------------------- ### AnalyserNode Configuration Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/ADVANCED.md Configures the AnalyserNode for audio analysis, setting the FFT size for frequency resolution and the smoothing time constant for averaging. These parameters control the granularity and responsiveness of the analysis data. ```typescript const analyser = audioContext.createAnalyser(); analyser.fftSize = 2048; // Power of 2 analyser.smoothingTimeConstant = 0.8; // 0-1 ``` -------------------------------- ### Mocking MediaRecorder for Unit Tests Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/ADVANCED.md Shows how to mock the `MediaRecorder` API using Jest for unit testing purposes. This enables testing components that interact with `MediaRecorder` without needing actual microphone access. ```typescript global.MediaRecorder = jest.fn((stream) => ({ start: jest.fn(), stop: jest.fn(), pause: jest.fn(), resume: jest.fn(), ondataavailable: null, onstop: null, onerror: null, state: "recording", })); ``` -------------------------------- ### Record with Fixed Width Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/QUICK-REFERENCE.md Integrate a fixed-width live streaming recorder component into your application. ```typescript const { mediaRecorder } = useAudioRecorder(); ``` -------------------------------- ### SSR Safe Rendering with Suspense Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/ADVANCED.md Demonstrates how to use `Suspense` for SSR-safe rendering of `AudioWaveform`. On the server, it returns a Suspense promise, and on the client, it decodes the audio and renders the waveform. ```typescript }> ``` -------------------------------- ### Main Library Exports Source: https://github.com/semanticist21/react-audio-wavekit/blob/main/_autodocs/MODULES.md Exports from the main library entry point, including components, hooks, and types. ```typescript // Components export { LiveRecorder } from "./recorder/live-recorder/index.js"; export { LiveStreamingRecorder } from "./recorder/live-streaming/recorder/recorder-compound.js"; export { LiveStreamingStackRecorder } from "./recorder/live-streaming/stack-recorder/stack-recorder-compound.js"; export { AudioWaveform } from "./waveform/index.js"; // Hooks export { useAudioRecorder } from "./recorder/use-audio-recorder.js"; // Types export type { UseAudioRecorderReturn } from "./recorder/use-audio-recorder.js"; export type { AudioWaveformAppearance, ScrollbarAppearance, WaveformAppearance } from "./types.js"; ```