bpm-finder
v1.0.1
Published
A simple and accurate BPM (Beats Per Minute) detection library for audio files in the browser
Maintainers
Readme
BPM Finder for npm
A simple and accurate BPM (Beats Per Minute) detection library for audio files in the browser.
Built on top of the proven web-audio-beat-detector library, this package provides a clean, easy-to-use API for analyzing audio files and detecting their tempo using the Web Audio API.
Features
- 🎵 Accurate BPM Detection: Uses dual-algorithm approach for reliable results
- 🚀 Multiple Analysis Modes: Full analysis, quick estimation, or tempo-only
- 🎛️ Customizable Tempo Ranges: Set min/max tempo for genre-specific analysis
- 🎼 Genre Presets: Built-in tempo ranges for different music genres
- 📁 Multiple Input Formats: Support for File objects, ArrayBuffer, and Uint8Array
- 🌐 Browser Native: Uses Web Audio API for audio decoding and processing
- 📊 Confidence Scoring: Get confidence levels for analysis results
- ⚡ High Performance: Efficient client-side processing
- 🛠️ TypeScript Support: Full type definitions included
- 🔒 Privacy First: All processing happens in the browser
Installation
npm install bpm-finderQuick Start
import { analyzeBPM } from 'bpm-finder';
// Analyze a file from input element
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const result = await analyzeBPM(file);
console.log(`BPM: ${result.bpm}, Confidence: ${result.confidence}%`);API Reference
Basic Usage
analyzeBPM(audioInput, options?)
Analyze BPM with full result information including confidence score.
import { analyzeBPM } from 'bpm-finder';
// From File object
const file = document.querySelector('input[type="file"]').files[0];
const result = await analyzeBPM(file);
// With options
const result = await analyzeBPM(file, {
minTempo: 120,
maxTempo: 140,
offset: 10, // Start analysis at 10 seconds
duration: 30 // Analyze 30 seconds
});
console.log(result);
// {
// bpm: 128,
// tempo: 128.5,
// confidence: 85,
// duration: 180,
// offset: 0.23
// }getTempo(audioInput, options?)
Get just the tempo value as a number.
import { getTempo } from 'bpm-finder';
const file = document.querySelector('input[type="file"]').files[0];
const tempo = await getTempo(file);
console.log(`Tempo: ${tempo} BPM`);quickEstimate(audioInput, options?)
Get a quick BPM estimation (faster but less accurate).
import { quickEstimate } from 'bpm-finder';
const file = document.querySelector('input[type="file"]').files[0];
const result = await quickEstimate(file);
console.log(`Quick BPM: ${result.bpm}`);Input Types
The library supports multiple input formats:
// File path (string)
await analyzeBPM('./music.mp3');
// Node.js Buffer
const buffer = fs.readFileSync('./music.mp3');
await analyzeBPM(buffer);
// ArrayBuffer
await analyzeBPM(arrayBuffer);
// Uint8Array
await analyzeBPM(uint8Array);Genre Presets
Use predefined tempo ranges optimized for different music genres:
import { getGenreSettings, analyzeBPM } from 'bpm-finder';
// Get tempo range for house music (115-135 BPM)
const houseSettings = getGenreSettings('house');
const result = await analyzeBPM('./house-track.mp3', houseSettings);
// Available genres:
// 'electronic', 'house', 'techno', 'trance', 'dubstep', 'dnb',
// 'hiphop', 'rock', 'pop', 'classical', 'jazz', 'reggae', 'latin', 'ambient'Advanced Usage
Using the BPMAnalyzer Class
import { BPMAnalyzer } from 'bpm-finder';
const analyzer = BPMAnalyzer.getInstance();
// Full analysis
const result = await analyzer.analyzeBPM('./music.mp3');
// Tempo only
const tempo = await analyzer.analyzeTempoOnly('./music.mp3');
// Quick estimate
const estimate = await analyzer.quickEstimate('./music.mp3');
// Cleanup (optional)
BPMAnalyzer.cleanup();Options
interface BPMOptions {
minTempo?: number; // Minimum tempo to detect (default: 60)
maxTempo?: number; // Maximum tempo to detect (default: 180)
offset?: number; // Start offset in seconds
duration?: number; // Analysis duration in seconds
}Result Format
interface BPMResult {
bpm: number; // Rounded BPM value
tempo: number; // Precise tempo value
confidence: number; // Confidence score (0-100)
duration: number; // Audio duration in seconds
offset?: number; // Offset of first beat in seconds
}Supported Formats
- MP3 (.mp3)
- WAV (.wav)
- FLAC (.flac)
- AAC (.aac)
- OGG (.ogg)
- M4A (.m4a)
Error Handling
import { analyzeBPM, AudioProcessingError } from 'bpm-finder';
try {
const result = await analyzeBPM('./music.mp3');
console.log(result);
} catch (error) {
if (error instanceof AudioProcessingError) {
console.error(`Audio processing error: ${error.message}`);
console.error(`Error code: ${error.code}`);
}
}Error codes:
INVALID_FILE: File not found or invalidUNSUPPORTED_FORMAT: Audio format not supportedDECODE_FAILED: Could not decode audio dataANALYSIS_FAILED: BPM analysis failedFILE_TOO_LARGE: Audio file exceeds size limits
Performance Tips
- Use appropriate tempo ranges: Narrow tempo ranges improve accuracy and speed
- Analyze shorter segments: Use
offsetanddurationoptions for faster processing - Use
quickEstimate(): For faster results when accuracy is less critical - Cache results: Store analysis results to avoid re-processing the same files
Examples
Batch Processing
import { analyzeBPM } from 'bpm-finder';
import { glob } from 'glob';
async function analyzeFolder(pattern: string) {
const files = glob.sync(pattern);
const results = [];
for (const file of files) {
try {
const result = await analyzeBPM(file);
results.push({ file, ...result });
console.log(`${file}: ${result.bpm} BPM (${result.confidence}%)`);
} catch (error) {
console.error(`Failed to analyze ${file}:`, error.message);
}
}
return results;
}
// Analyze all MP3 files in a directory
const results = await analyzeFolder('./music/*.mp3');Tempo-based Classification
import { analyzeBPM } from 'bpm-finder';
function classifyTempo(bpm: number): string {
if (bpm < 60) return 'Very Slow';
if (bpm < 80) return 'Slow';
if (bpm < 120) return 'Moderate';
if (bpm < 140) return 'Fast';
if (bpm < 180) return 'Very Fast';
return 'Extremely Fast';
}
const result = await analyzeBPM('./music.mp3');
const classification = classifyTempo(result.bpm);
console.log(`${result.bpm} BPM - ${classification}`);Requirements
- Node.js >= 14.0.0
- Supported audio codecs installed on system
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Credits
Built on top of:
- web-audio-beat-detector - Core BPM detection algorithm
- audio-decode - Audio file decoding
- audio-buffer - AudioBuffer polyfill
