beat-tracker
v1.0.3
Published
A lightweight beat tracking library for the browser
Maintainers
Readme
BeatTracker
A lightweight, pure JavaScript beat tracking library for the browser. It uses Web Workers for off-main-thread processing and FFT for spectral analysis to detect beats in audio files.
Note: The current version performs best with piano music.
Features
- Web Worker Support: Performs heavy computations (FFT, spectral flux) in a background thread to keep the UI responsive.
- Spectral Flux Analysis: Uses frequency domain analysis to detect onset strength.
- Intelligent Beat Tracking: Implements an agent-based approach with tempo induction and phase alignment.
- Zero External Dependencies: Self-contained logic using only native Web APIs.
Installation
This is a standalone module. Copy the src folder to your project.
Usage
Basic Usage
import { beatsEval } from './path/to/BeatTracker.js';
// Get an AudioBuffer (e.g., from AudioContext.decodeAudioData)
const audioContext = new AudioContext();
const response = await fetch('music.mp3');
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
// Analyze beats
try {
const beatSamples = await beatsEval(audioBuffer, (progress) => {
console.log(`Progress: ${progress.progress * 100}%`);
});
console.log('Detected beat sample indices:', beatSamples);
// Convert samples to seconds
const beatTimes = beatSamples.map(sample => sample / audioBuffer.sampleRate);
console.log('Beat times (seconds):', beatTimes);
} catch (err) {
console.error('Beat tracking failed:', err);
}Finding Nearest Beat in Window
If you need to find a beat near a specific timestamp (e.g., for quantization or syncing):
import { findNearestBeatInWindow } from './path/to/BeatTracker.js';
const centerSample = 44100 * 10; // 10 seconds in
const result = await findNearestBeatInWindow(audioBuffer, centerSample);
console.log('Nearest beat sample:', result.nearestBeatSample);Running the Example
Due to browser security restrictions on Web Workers and ES Modules (CORS), you cannot run the example directly from the file system (file://). You must serve it via a local HTTP server.
Navigate to the project root:
cd /path/to/BeatTrackerStart a local server. For example, using Python:
# Python 3 python3 -m http.server 8000Or using Node.js
http-server:npx http-serverOpen your browser and visit:
http://localhost:8000/example/
Project Structure
BeatTracker/
├── src/
│ ├── BeatsTracker.js # Main entry point and logic
│ ├── SpectralFluxWorker.js # Web Worker for processing
│ └── fftv5.js # FFT implementation
├── example/
│ ├── index.html # Demo interface
│ └── app.js # Demo logic
└── README.mdLicense
MIT
