Realtime BPM Analyzer

repository·main·Indexed 43 days ago

https://github.com/dlepaux/realtime-bpm-analyzer

A TypeScript-first, zero-dependency library for real-time beats-per-minute (BPM) detection in the browser. It supports audio files, microphones, and streams using the Web Audio API and AudioWorklet. Version 5.0.15 provides methods like analyzeFullBuffer for offline analysis and createRealtimeBpmAnalyzer() for live detection, with official integration examples for Vanilla JS, React 18, and Vue 3.

Tokens
31.5K
Snippets
84
Records
128
Agent score
52%

What's inside Realtime BPM Analyzer

  1. Overview of Realtime BPM Analyzer

    main

    Realtime BPM Analyzer is a lightweight (< 5KB gzipped), zero-dependency TypeScript/JavaScript library designed to detect beats-per-minute (BPM) or tempo directly in the browser. It is framework-agnostic and leverages the Web Audio API's AudioWorkletProcessor for high-performance, real-time analysis.

    Key Capabilities

    • Real-Time Analysis: Provides continuous updates and stable BPM detection events while audio/video is playing.
    • Multiple Input Sources: Supports HTML <audio> and <video> elements, file uploads (MP3, FLAC, WAV), microphone/getUserMedia streams, and network audio streams.
    • Accurate Detection: Uses amplitude threshold scanning, interval analysis, and tempo grouping to identify patterns in peak timing.
    • TypeScript Support: Includes complete type definitions for type safety and IDE integration.
  2. Analyze BPM from streaming audio URLs in React

    main

    The React streaming implementation provides the following capabilities for real-time audio analysis:

    • Streaming Audio: Load and play audio streams directly from URLs.
    • BPM Detection: Use createRealtimeBpmAnalyzer() to perform real-time BPM detection on the incoming stream.
    • Audio Processing: Apply audio filtering using getBiquadFilter().
    • Playback Management: Includes controls for play, pause, and stop.
    • Lifecycle Management: Ensures proper cleanup and resource management within the React component lifecycle.
  3. Key features of the React integration

    main

    The React implementation of the Realtime BPM Analyzer provides a modern component architecture designed for offline BPM analysis. Key technical features include:

    • React 18 & TypeScript: Full type safety and support for modern React features.
    • Custom Hooks: Specialized hooks for managing the AudioContext lifecycle.
    • Offline Analysis: Uses the analyzeFullBuffer method for processing audio data.
    • Resource Management: Implements proper cleanup and error handling to prevent memory leaks and handle audio context interruptions.
  4. Real-time BPM detection with Vue 3 and Microphone

    main

    The Vue Microphone example demonstrates how to implement real-time BPM (Beats Per Minute) analysis using microphone input within a Vue 3 application.

    Key implementation details include:

    • Utilizing createRealtimeBpmAnalyzer() to initialize the analyzer.
    • Managing microphone permissions via the browser API.
    • Implementing start/stop recording controls.
    • Using the Vue 3 Composition API with the <script setup> syntax for reactive state management.
  5. How Realtime BPM Analyzer handles audio privacy

    main

    Realtime BPM Analyzer is designed for local, client-side processing. All audio analysis is performed entirely within the user's browser using the Web Audio API.

    Key Privacy Characteristics:

    • Local Processing: Analysis runs in an AudioWorklet (a separate thread) within the browser. No audio data is sent to external servers.
    • No Storage: The library does not record, store, or cache audio files, telemetry, or user information.
    • Zero Dependencies: The library has zero runtime dependencies and makes no external API calls during processing.
    • Memory Management: Audio is processed in small chunks with temporary buffers that are cleared after analysis to prevent persistent storage in memory.
  6. How streaming audio BPM detection works

    main
    Streaming analysis functions by bridging a standard HTML audio element into the Web Audio API graph. Instead of capturing microphone input, you use audioContext.createMediaElementSource(audioElement) to create a node representing the audio stream. This node is then piped through the bpmAnalyzer.node. This allows for real-time, low-latency BPM detection of HTTP/HTTPS streams (MP3, AAC, etc.) while maintaining the ability to route the audio to the speakers via audioContext.destination.
  7. Choose a BPM analysis usage mode

    main

    The library provides three distinct modes for analyzing audio depending on your source and requirements:

    1. Real-Time Analysis (Default): Best for music or video players with defined lengths. It accumulates data throughout playback to increase accuracy over time without resetting.
    2. Continuous Analysis (Auto-Reset): Best for infinite streams like radio or live broadcasts. It automatically resets after a stabilizationTime to prevent memory buildup.
    3. Offline/Buffer Analysis: Best for batch processing or file uploads. It processes an entire audio buffer at once for the fastest possible results.

    Use createRealtimeBpmAnalyzer for real-time or continuous modes, and analyzeFullBuffer for offline analysis.

    // Real-Time (Default)
    const bpmAnalyzer = await createRealtimeBpmAnalyzer(audioContext);
    
    // Continuous (Auto-Reset)
    const bpmAnalyzer = await createRealtimeBpmAnalyzer(audioContext, {
      continuousAnalysis: true,
      stabilizationTime: 20000 // Reset every 20 seconds
    });
    
    // Offline/Buffer Analysis
    import { analyzeFullBuffer } from 'realtime-bpm-analyzer';
    const buffer = await audioContext.decodeAudioData(arrayBuffer);
    const tempos = await analyzeFullBuffer(buffer);
  8. How Realtime BPM Analyzer works

    main

    The library performs real-time audio analysis using the AudioWorkletProcessor via the Web Audio API. The processing pipeline follows these steps:

    1. Audio Input: Captures audio from the source (e.g., <audio> element, microphone, or file).
    2. Filtering: Optionally applies a low-pass filter to isolate bass frequencies for better peak detection.
    3. Peak Detection: Identifies signal peaks at various threshold levels.
    4. Interval Analysis: Calculates the time intervals between detected peaks.
    5. BPM Calculation: Converts these intervals into BPM values and groups similar tempos.
    6. Result Output: Emits BPM candidates along with confidence scores.
  9. Understand BPM analyzer events

    main

    The bpmAnalyzer instance is an event emitter that provides two primary event types for tracking tempo:

    bpm Event

    • Frequency: Emitted frequently during analysis.
    • Payload: Contains multiple BPM candidates with confidence scores.
    • Behavior: Values may fluctuate as more audio data is processed.
    • Use Case: Best for real-time UI updates or progressive analysis where you want to show the analyzer's current
  10. Handling remote audio streams and CORS

    main

    If your application uses the library to analyze remote audio (via URLs or streams), note the following:

    • Direct Fetching: The browser fetches the audio directly. The library does not intercept or proxy the audio data.
    • CORS Requirements: Remote audio sources must be configured to allow Cross-Origin Resource Sharing (CORS). If the server hosting the audio does not allow your domain, the browser will block the request.
    • Privacy Responsibility: Privacy for remote streams depends on the audio source provider, as the library itself does not interact with the source beyond the browser's standard fetching mechanism.
  11. Choose a BPM analysis use case

    main

    The realtime-bpm-analyzer supports three primary analysis patterns depending on your audio source and requirements:

    1. Basic / Offline Analysis

    Method: analyzeFullBuffer
    Best for: File uploads where you need fast, accurate BPM detection without requiring audio playback. Output: Returns an array of BPM candidates.

    2. Streaming Audio

    Method: createRealtimeBpmAnalyzer + MediaElementSource
    Best for: Analyzing BPM from streaming URLs (e.g., internet radio, remote audio files) during playback. Implementation Detail: Uses getBiquadFilter() for processing. The audio graph connection follows: source → filter → analyzer.node → destination. Event: Listens for the bpmStable event.

    3. Microphone Input

    Method: createRealtimeBpmAnalyzer + MediaStreamSource
    Best for: Live BPM detection from microphones, instruments, or any live audio input. Implementation Detail: Requires microphone permissions. The audio graph connection follows: source → analyser and source → analyzer.node. Cleanup: Requires calling suspend() and disconnect() to release resources.