### Install web-audio-beat-detector Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Install the package using npm. ```shell npm install web-audio-beat-detector ``` -------------------------------- ### Custom Tempo Range Examples Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/00-START-HERE.md Examples of configuring tempo ranges for different music genres. Adjust minTempo and maxTempo to suit the expected beat patterns. ```javascript // Electronic music (fast) { minTempo: 120, maxTempo: 160 } // Pop/Hip-Hop (moderate) { minTempo: 85, maxTempo: 130 } // Ambient (slow) { minTempo: 40, maxTempo: 100 } ``` -------------------------------- ### Error Handling Example Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Illustrates a potential error scenario where no coherent beat pattern is detected in the audio, causing the Promise to reject. ```javascript // "The given channelData does not contain any detectable beats." ``` -------------------------------- ### TempoSettings Examples Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/types.md Demonstrates how to create and apply `TempoSettings` objects to filter beat detection results for specific tempo ranges like fast, slow, or pop music. ```javascript // Detect only fast music (120-180 BPM) const fastMusicSettings = { minTempo: 120, maxTempo: 180 }; // Detect only slow music (40-100 BPM) const slowMusicSettings = { minTempo: 40, maxTempo: 100 }; // Detect typical pop/dance music (85-130 BPM) const popMusicSettings = { minTempo: 85, maxTempo: 130 }; // Apply settings to analyze const tempo = await analyze(audioBuffer, 0, undefined, fastMusicSettings); // Apply settings to guess const result = await guess(audioBuffer, undefined, undefined, slowMusicSettings); ``` -------------------------------- ### Analyze Specific Sections of Audio Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Demonstrates how to analyze only a portion of an audio buffer by specifying an offset and duration. The first example analyzes from 30s to 60s, while the second analyzes a 30s section starting at 20s. ```javascript import { analyze } from 'web-audio-beat-detector'; async function analyzeChorus(audioBuffer) { // Skip intro (0-30s), analyze chorus (30-60s) const chorusOffset = 30; const chorusDuration = 30; return await analyze( audioBuffer, chorusOffset, chorusDuration ); } async function analyzeMainSection(audioBuffer) { // Skip intro (20s), analyze main section (30s) return await analyze(audioBuffer, 20, 30); } ``` -------------------------------- ### Tempo Range Enforcement Example (Standard) Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Demonstrates the standard tempo range configuration, which provides a balance between accuracy and flexibility for general music analysis. ```javascript const standardRange = { minTempo: 90, maxTempo: 180 }; ``` -------------------------------- ### Example Output Structure Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Illustrates the expected output format from beat detection functions, showing the structure of the returned object with `bpm`, `tempo`, and `offset` properties. ```javascript // For a file detected as 129.6 BPM with first beat at 0.213 seconds: // { // bpm: 130, // tempo: 129.6, // offset: 0.21255712541426797 // } ``` -------------------------------- ### Tempo Range Enforcement Example (Narrow) Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Demonstrates a narrow tempo range configuration where minTempo and maxTempo are set to the same value. This enforces a very specific tempo. ```javascript const narrowRange = { minTempo: 128, maxTempo: 128 // or omit maxTempo for +∞ }; ``` -------------------------------- ### Batch Process Audio Files Sequentially Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md This example demonstrates how to process multiple audio files sequentially. It iterates through a list of files, decodes each one, analyzes its tempo, and collects the results, including any errors encountered. ```javascript import { analyze } from 'web-audio-beat-detector'; async function analyzeAudioFiles(files) { const results = []; for (const file of files) { try { const arrayBuffer = await file.arrayBuffer(); const audioContext = new AudioContext(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); const tempo = await analyze(audioBuffer); results.push({ filename: file.name, tempo, success: true }); } catch (error) { results.push({ filename: file.name, error: error.message, success: false }); } } return results; } // Usage const files = [file1, file2, file3]; const results = await analyzeAudioFiles(files); console.table(results); // [ // { filename: 'song1.mp3', tempo: 120, success: true }, // { filename: 'song2.mp3', tempo: 130.5, success: true }, // { filename: 'song3.wav', error: '...', success: false } // ] ``` -------------------------------- ### Dynamic Import Pattern Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Example of using dynamic import to load the analyze and guess functions asynchronously. ```javascript const { analyze, guess } = await import('web-audio-beat-detector'); ``` -------------------------------- ### GuessResult Examples Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/types.md Shows how to access and utilize the `bpm`, `tempo`, and `offset` fields from a `GuessResult` object for displaying tempo information and calculating beat timings. ```javascript const result = await guess(audioBuffer); // Access individual fields console.log(`BPM: ${result.bpm}`); // e.g., 130 console.log(`Precise tempo: ${result.tempo}`); // e.g., 129.6 console.log(`First beat at: ${result.offset}s`); // e.g., 0.213 // Calculate beat timing const beatInterval = 60 / result.tempo; // seconds between beats const secondBeatTime = result.offset + beatInterval; // Use in animations function scheduleBeatsAnimation() { let nextBeatTime = result.offset; const beatDuration = 60 / result.bpm; const animationLoop = setInterval(() => { // Schedule beat animation const timeUntilBeat = nextBeatTime - audio.currentTime; setTimeout(() => { triggerBeatAnimation(); }, timeUntilBeat * 1000); nextBeatTime += beatDuration; }, beatDuration * 1000); } ``` -------------------------------- ### Analyze Audio from MediaElementAudioSourceNode Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md This example outlines the approach for analyzing audio originating from a `MediaElementAudioSourceNode`. Note that for direct buffer analysis, fetching and decoding is typically used instead of this method. ```javascript import { guess } from 'web-audio-beat-detector'; async function analyzeMediaElement(audioElement) { // Create offline context with same sample rate as audio element const offlineContext = new OfflineAudioContext( audioElement.channels || 1, audioElement.duration * 44100, // sample count 44100 ); // Note: Decoding happens automatically when playing // For raw buffer analysis, use fetch + decodeAudioData pattern above } ``` -------------------------------- ### Lazy Loading Worker Example Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/broker-pattern.md Illustrates the lazy initialization of a Web Worker. The worker is created and cached only upon the first call to `analyze()`, improving startup performance. ```javascript const loadOrReturnBroker = createLoadOrReturnBroker(load, worker); // First call: worker is created and cached const tempo1 = await analyze(audioBuffer1); // Second call: cached worker is reused const tempo2 = await analyze(audioBuffer2); ``` -------------------------------- ### Get Tempo and Beat Offset with guess() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Analyze an AudioBuffer to detect the tempo and beat offset. Imports the 'guess' function from the library. ```javascript const { bpm, tempo: preciseTempo, offset } = await guess(audioBuffer); console.log(`BPM: ${bpm}, Offset: ${offset}s`); ``` -------------------------------- ### Interval Grouping Example Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/algorithm.md Demonstrates how peak indices are used to calculate temporal spacing and group them by interval. This helps in identifying recurring rhythmic patterns. ```text Peak positions: [100, 250, 400, 550, 750, 900, ...] Intervals: [150, 150, 150, 200, 150, ...] Grouped by interval: - Interval 150: 4 peaks (indices 100→250→400→550, 550→750) - Interval 200: 1 peak (750→900) - Interval 100: ... ``` -------------------------------- ### Result Selection Example Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/algorithm.md Illustrates the final step where the tempo candidate with the highest score is selected as the detected tempo. This shows a ranked list of candidates and the chosen result. ```text Tempo candidates (sorted by score): 1. 130 BPM (score: 45.3) ← SELECTED 2. 129 BPM (score: 42.1) 3. 260 BPM (score: 18.5) (octave of 130) 4. 65 BPM (score: 12.2) (octave of 130) 5. 95 BPM (score: 8.7) ``` -------------------------------- ### Tempo Range Enforcement Example (Wide) Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Demonstrates a wide tempo range configuration, suitable for catching unusual or unexpected tempos in diverse or experimental music. ```javascript const wideRange = { minTempo: 40, maxTempo: 200 }; ``` -------------------------------- ### Analyze User-Selected Audio File Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Provides an example of analyzing audio from a file selected by the user via an HTML input element. The selected file is read as an ArrayBuffer, decoded, and then analyzed using the `guess` function. ```javascript import { guess } from 'web-audio-beat-detector'; async function analyzeUserSelectedFile(file) { // Read file as ArrayBuffer const arrayBuffer = await file.arrayBuffer(); // Decode const audioContext = new (window.AudioContext || window.webkitAudioContext)(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); // Analyze return await guess(audioBuffer); } // Usage with HTML input document.getElementById('audioInput').addEventListener('change', async (event) => { const file = event.target.files[0]; const result = await analyzeUserSelectedFile(file); console.log(`Detected: ${result.bpm} BPM`); }); ``` -------------------------------- ### Error Handling with Broker (JavaScript) Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/broker-pattern.md The factory delegates error handling to the broker and worker. This example shows how to catch errors during analysis performed by the broker. ```javascript const loadOrReturnBroker = createLoadOrReturnBroker(load, worker); try { const result = await loadOrReturnBroker().analyze(audioBuffer); } catch (error) { // Error from worker computation console.error('Analysis failed:', error.message); } ``` -------------------------------- ### Handle Specific Beat Detection Errors Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md This example demonstrates how to specifically catch and handle errors related to beat detection failures. It differentiates between a 'no detectable beats' error and other unexpected errors. ```javascript import { guess } from 'web-audio-beat-detector'; async function guessWithSpecificHandling(audioBuffer) { try { return await guess(audioBuffer); } catch (error) { if (error.message.includes('does not contain any detectable beats')) { // Handle beat detection failure return null; // Indicate no beats detected } else { // Handle unexpected errors throw error; } } } ``` -------------------------------- ### Get BPM, Tempo, and Offset with guess() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Utilize the `guess` function to obtain detailed beat information, including rounded BPM, precise tempo, and the timing of the first beat. This function is useful for applications requiring more granular beat data. ```javascript import { guess } from 'web-audio-beat-detector'; const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); const result = await guess(audioBuffer); console.log(`BPM: ${result.bpm}`); // Rounded BPM console.log(`Precise Tempo: ${result.tempo}`); // Floating-point console.log(`Beat Offset: ${result.offset}s`); // First beat timing ``` -------------------------------- ### Analyze Audio and Display Beat Information Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Analyzes an audio buffer to guess BPM, tempo, and the first beat offset. It then displays this information and starts a beat animation. ```javascript import { guess } from 'web-audio-beat-detector'; class BeatDisplay { constructor(audioElement) { this.audioElement = audioElement; this.result = null; } async analyze(audioBuffer) { this.result = await guess(audioBuffer); this.displayBeatInfo(); this.startBeatAnimation(); } displayBeatInfo() { console.log(`BPM: ${this.result.bpm}`); console.log(`Precise Tempo: ${this.result.tempo}`); console.log(`First beat: ${this.result.offset.toFixed(2)}s`); } startBeatAnimation() { if (!this.result) return; const beatInterval = 60 / this.result.tempo; let nextBeatTime = this.result.offset; const update = () => { if (!this.audioElement.playing) { requestAnimationFrame(update); return; } const currentTime = this.audioElement.currentTime; // Trigger beat visual if (currentTime >= nextBeatTime) { this.flashBeat(); nextBeatTime += beatInterval; } requestAnimationFrame(update); }; update(); } flashBeat() { console.log('🥁 Beat!'); // Update UI, play sound, etc. } } ``` -------------------------------- ### Package Structure Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/README.md Illustrates the directory layout of the web-audio-beat-detector project, showing the organization of source files, build outputs, and configuration. ```bash web-audio-beat-detector/ ├── src/ │ ├── module.ts # Main exports │ ├── factories/ │ │ └── load-or-return-broker.ts # Broker caching │ └── worker/ │ └── worker.ts # Minified worker script ├── build/ │ ├── es5/ # CommonJS build │ └── es2019/ # ES module build ├── package.json └── README.md ``` -------------------------------- ### Analyze AudioBuffer tempo Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Use the analyze function with an AudioBuffer to get the tempo. Handles errors with a catch block. ```javascript analyze(audioBuffer) .then((tempo) => { // the tempo could be analyzed }) .catch((err) => { // something went wrong }); ``` -------------------------------- ### Analyze Audio from a File Path Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Demonstrates how to load and analyze an audio file directly from a given file path. This involves fetching the file, decoding it into an AudioBuffer, and then passing it to the `analyze` function. ```javascript import { analyze } from 'web-audio-beat-detector'; async function analyzeAudioFile(filePath) { // Fetch the file const response = await fetch(filePath); const arrayBuffer = await response.arrayBuffer(); // Create audio context and decode const audioContext = new (window.AudioContext || window.webkitAudioContext)(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); // Analyze return await analyze(audioBuffer); } // Usage const tempo = await analyzeAudioFile('/audio/song.mp3'); ``` -------------------------------- ### Analyze with All Parameters Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Demonstrates the use of all available parameters for the analyze function, including audio buffer, offset, duration, and custom tempo settings. ```javascript // Complete parameter specification const tempo = await analyze( audioBuffer, // AudioBuffer 10, // offset: 10 seconds 30, // duration: 30 seconds { minTempo: 100, maxTempo: 160 } ); ``` -------------------------------- ### Guess BPM and offset from AudioBuffer Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Use the guess function with an AudioBuffer to get BPM, offset, and tempo. Handles errors with a catch block. ```javascript guess(audioBuffer) .then(({ bpm, offset, tempo }) => { // the bpm and offset could be guessed // the tempo is the same as the one returned by analyze() }) .catch((err) => { // something went wrong }); ``` -------------------------------- ### Basic guess() Usage Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/guess.md Demonstrates how to use the guess() function with default settings to detect BPM, tempo, and the first beat offset from an AudioBuffer. Includes error handling for cases where no beats are detected. ```javascript import { guess } from 'web-audio-beat-detector'; const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); try { const result = await guess(audioBuffer); console.log(`BPM: ${result.bpm}`); console.log(`Precise Tempo: ${result.tempo} BPM`); console.log(`First beat offset: ${result.offset} seconds`); } catch (err) { console.error('Beat detection failed:', err.message); } ``` -------------------------------- ### Analyze Partial Audio Segment Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Analyze a specific segment of an AudioBuffer by providing start time and duration. Skips the initial part of the audio. ```javascript import { analyze } from 'web-audio-beat-detector'; // Skip intro (0-30s), analyze next 30 seconds const tempo = await analyze(audioBuffer, 30, 30); ``` -------------------------------- ### Complete Algorithm Flow Diagram Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/algorithm.md Visualizes the sequential steps of the beat detection algorithm, from audio buffer input to offset calculation output. ```text Audio Buffer ↓ [Step 1] Peak Detection ↓ (peak indices) [Step 2] Interval Grouping ↓ (intervals with peak counts) [Step 3] Tempo Candidate Generation ↓ (tempo values in BPM) [Step 4] Tempo Scoring ↓ (tempos with scores) [Step 5] Result Selection ↓ analyze(): returns best tempo (number) guess(): also calculates [Step 6] offset ↓ [Step 6] Offset Calculation ↓ guess(): returns { bpm, tempo, offset } ``` -------------------------------- ### Initialize Visualization Dashboard with Beat Info Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Initializes a visualization dashboard by guessing beat information from an audio buffer. This is useful for real-time audio analysis and display. ```javascript import { guess } from 'web-audio-beat-detector'; class MusicVisualization { async initialize(audioBuffer) { this.beatInfo = await guess(audioBuffer); this.updateDashboard(); } updateDashboard() { const { bpm, tempo, offset } = this.beatInfo; const beatInterval = 60 / tempo; document.getElementById('bpm-display').textContent = bpm; document.getElementById('tempo-display').textContent = tempo.toFixed(2); document.getElementById('offset-display').textContent = offset.toFixed(3); document.getElementById('interval-display').textContent = beatInterval.toFixed(3); this.renderGenreHint(); this.renderTempoHistory(); } renderGenreHint() { const bpm = this.beatInfo.bpm; let genre = 'Unknown'; if (bpm < 90) genre = 'Ambient/Slow'; else if (bpm < 120) genre = 'Pop/R&B'; else if (bpm < 140) genre = 'Rock/Dance'; else if (bpm < 160) genre = 'Electronic/Techno'; else genre = 'Fast/Drum & Bass'; document.getElementById('genre-hint').textContent = genre; } renderTempoHistory() { // Track tempos over time for visualization if (!this.tempoHistory) this.tempoHistory = []; this.tempoHistory.push(this.beatInfo.tempo); // Keep last 10 analyses if (this.tempoHistory.length > 10) { this.tempoHistory.shift(); } const ctx = document.getElementById('tempo-chart').getContext('2d'); // Update chart with history data } } ``` -------------------------------- ### Importing and Using Analyze and Guess Functions Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/types.md Demonstrates how to import the analyze and guess functions from the 'web-audio-beat-detector' module and use them with an AudioBuffer. Type inference is used for the returned values. ```typescript import { analyze, guess } from 'web-audio-beat-detector'; // Types are implicit in the function signatures const tempo: number = await analyze(audioBuffer); const result: GuessResult = await guess(audioBuffer); ``` -------------------------------- ### Analyze Audio Files in Parallel Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md This snippet shows how to analyze multiple audio files concurrently using `Promise.all`. This approach significantly speeds up processing when dealing with many files. ```javascript import { analyze } from 'web-audio-beat-detector'; async function analyzeFilesInParallel(files) { const analysisPromises = files.map(async (file) => { try { const arrayBuffer = await file.arrayBuffer(); const audioContext = new AudioContext(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); const tempo = await analyze(audioBuffer); return { filename: file.name, tempo, success: true }; } catch (error) { return { filename: file.name, error: error.message, success: false }; } }); return await Promise.all(analysisPromises); } // Much faster for multiple files const results = await analyzeFilesInParallel(fileArray); ``` -------------------------------- ### Module Implementation Details Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Shows how the analyze and guess functions are implemented as thin wrappers delegating to a broker created by a factory. Actual computation occurs in a Web Worker. ```typescript // From src/module.ts import { load } from 'web-audio-beat-detector-broker'; import { createLoadOrReturnBroker } from './factories/load-or-return-broker'; import { worker } from './worker/worker'; const loadOrReturnBroker = createLoadOrReturnBroker(load, worker); export const analyze: ReturnType['analyze'] = (...args) => loadOrReturnBroker().analyze(...args); export const guess: ReturnType['guess'] = (...args) => loadOrReturnBroker().guess(...args); ``` -------------------------------- ### Configuration Options Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/INDEX.md Configuration options for tempo detection, including minimum and maximum BPM thresholds. ```typescript minTempo: number (default: 90) ``` ```typescript maxTempo: number (default: 180) ``` -------------------------------- ### Basic Beat Detection with analyze() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Analyze an AudioBuffer to detect the tempo. Imports the 'analyze' function from the library. ```javascript import { analyze, guess } from 'web-audio-beat-detector'; // Get tempo const tempo = await analyze(audioBuffer); console.log(`Tempo: ${tempo} BPM`); ``` -------------------------------- ### Analyze Tempo and Guess Beat Offset Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/00-START-HERE.md Use analyze() to detect tempo and guess() to get tempo and beat offset. You can optionally provide custom tempo range settings. ```javascript import { analyze, guess } from 'web-audio-beat-detector'; // Detect tempo const tempo = await analyze(audioBuffer); console.log(`Tempo: ${tempo} BPM`); // Detect tempo + beat offset const result = await guess(audioBuffer); console.log(`BPM: ${result.bpm}, First beat: ${result.offset}s`); // Custom tempo range const result = await guess(audioBuffer, 0, undefined, { minTempo: 120, maxTempo: 160 }); ``` -------------------------------- ### Analyze Specific Audio Segment Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/analyze.md Analyze a portion of an audio buffer by specifying the start offset and duration in seconds. This is useful for analyzing specific sections of longer audio files. ```javascript // Analyze 30 seconds of audio starting at 10 seconds const tempo = await analyze(audioBuffer, 10, 30); ``` -------------------------------- ### Analyze Audio from File Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Fetch an audio file, decode it using AudioContext, and then analyze its tempo. Requires fetch, AudioContext, and decodeAudioData. ```javascript import { analyze } from 'web-audio-beat-detector'; // Fetch and decode audio const response = await fetch('song.mp3'); const arrayBuffer = await response.arrayBuffer(); const audioContext = new AudioContext(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); // Analyze const tempo = await analyze(audioBuffer); ``` -------------------------------- ### Custom Tempo Range for Different Music Genres with guess() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/guess.md Demonstrates how to use the tempoSettings parameter with guess() to specify a custom tempo range, optimizing detection for different music genres like techno, pop, or acoustic. ```javascript // For electronic music (faster) const technoResult = await guess(audioBuffer, 0, undefined, { minTempo: 120, maxTempo: 180 }); // For hip-hop/pop (moderate) const popResult = await guess(audioBuffer, 0, undefined, { minTempo: 85, maxTempo: 125 }); // For acoustic/ambient (slower) const acousticResult = await guess(audioBuffer, 0, undefined, { minTempo: 60, maxTempo: 100 }); ``` -------------------------------- ### Import guess function Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Import the guess function for estimating BPM and beat offset. ```javascript import { guess } from 'web-audio-beat-detector'; ``` -------------------------------- ### Module Usage of Broker Factory Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/broker-pattern.md Demonstrates how to use the `createLoadOrReturnBroker` factory to create and export thin wrapper functions for analyzing audio data. The worker is lazily loaded and cached. ```typescript import { load } from 'web-audio-beat-detector-broker'; import { createLoadOrReturnBroker } from './factories/load-or-return-broker'; import { worker } from './worker/worker'; const loadOrReturnBroker = createLoadOrReturnBroker(load, worker); export const analyze: ReturnType['analyze'] = (...args) => loadOrReturnBroker().analyze(...args); export const guess: ReturnType['guess'] = (...args) => loadOrReturnBroker().guess(...args); ``` -------------------------------- ### Analyze Audio Buffer for Tempo (JavaScript ES Module) Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/EXPORTS.md Import and use the analyze and guess functions from the 'web-audio-beat-detector' package in an ES Module environment. Type annotations are not required. ```javascript import { analyze, guess } from 'web-audio-beat-detector'; // Use without type annotations const tempo = await analyze(audioBuffer); const result = await guess(audioBuffer); ``` -------------------------------- ### Basic Usage: Detect Tempo and Beat Offset Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/README.md Demonstrates how to import and use the analyze and guess functions to detect tempo and beat offset from an AudioBuffer. Ensure you have an AudioContext and an ArrayBuffer containing audio data. ```javascript import { analyze, guess } from 'web-audio-beat-detector'; // Detect tempo const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); const tempo = await analyze(audioBuffer); console.log(`Detected tempo: ${tempo} BPM`); // Get tempo with beat offset const result = await guess(audioBuffer); console.log(`BPM: ${result.bpm}, Offset: ${result.offset}s`); ``` -------------------------------- ### Analyze AudioBuffer with tempo settings Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Analyze an AudioBuffer and specify the tempo range using tempoSettings. ```javascript analyze(audioBuffer, { maxTempo: 120, minTempo: 60 }); ``` -------------------------------- ### Handle Analysis Errors with Try-Catch Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Demonstrates basic error handling for beat detection using a try-catch block. This is essential for gracefully managing situations where beat detection might fail, such as with silent or non-musical audio data. ```javascript import { analyze } from 'web-audio-beat-detector'; try { const tempo = await analyze(audioBuffer); console.log(`Tempo: ${tempo}`); } catch (error) { console.error('Beat detection error:', error.message); // "The given channelData does not contain any detectable beats." } ``` -------------------------------- ### ES Modules Import Pattern Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Recommended import pattern for ES Modules. Shows how to import and use the analyze and guess functions. ```javascript import { analyze, guess } from 'web-audio-beat-detector'; const tempo = await analyze(audioBuffer); const result = await guess(audioBuffer); ``` -------------------------------- ### Import analyze function Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Import the analyze function for tempo detection. ```javascript import { analyze } from 'web-audio-beat-detector'; ``` -------------------------------- ### Basic Analyze Audio Buffer Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/analyze.md Use this snippet for a straightforward tempo detection of an entire audio buffer with default tempo settings. Ensure the AudioContext and AudioBuffer are properly initialized. ```javascript import { analyze } from 'web-audio-beat-detector'; const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); try { const tempo = await analyze(audioBuffer); console.log(`Detected tempo: ${tempo} BPM`); } catch (err) { console.error('Beat detection failed:', err.message); } ``` -------------------------------- ### Analyze Specific Audio Section with guess() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/guess.md Shows how to use the offset and duration parameters with guess() to analyze a specific portion of an AudioBuffer, such as the chorus. ```javascript // Analyze the chorus (30 seconds starting at 1 minute) const result = await guess(audioBuffer, 60, 30); console.log(`Chorus tempo: ${result.bpm} BPM`); console.log(`Chorus beat offset: ${result.offset} seconds`); ``` -------------------------------- ### Analyze AudioBuffer with offset, duration, and tempo settings Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/README.md Analyze a specific portion of an AudioBuffer by providing offset and duration. Customize tempo range using tempoSettings. ```javascript analyze(audioBuffer, 1, 10, { maxTempo: 120, minTempo: 60 }); ``` -------------------------------- ### Analyze Audio Buffer for Tempo (JavaScript CommonJS) Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/EXPORTS.md Import the analyze and guess functions using CommonJS syntax. The analyze function returns a Promise that resolves to the tempo, and errors can be caught using .catch(). ```javascript const { analyze, guess } = require('web-audio-beat-detector'); analyze(audioBuffer) .then(tempo => console.log(tempo)) .catch(err => console.error(err)); ``` -------------------------------- ### Synchronize Playback and Schedule Events with Detected Beats Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/guess.md Use the guess() function to detect tempo and offset, then synchronize audio playback and schedule events to specific beats. The beat interval is calculated from the tempo. ```javascript const result = await guess(audioBuffer); const beatInterval = 60 / result.tempo; // seconds per beat // Calculate the time of the nth beat after the first beat function getBeatTime(beatNumber) { return result.offset + (beatNumber * beatInterval); } // Start playback synchronized to the detected beat const firstBeatTime = result.offset; audio.currentTime = 0; audio.play(); // Schedule a callback for the second beat const secondBeatTime = getBeatTime(1); setTimeout(() => { console.log('Second beat reached'); }, secondBeatTime * 1000); ``` -------------------------------- ### Implement Fallback Tempo on Error Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Shows how to provide a default tempo value when beat detection fails. This pattern uses a try-catch block to return a predefined tempo if an error occurs during analysis, ensuring a fallback value is always available. ```javascript import { analyze } from 'web-audio-beat-detector'; const DEFAULT_TEMPO = 120; async function analyzeWithFallback(audioBuffer) { try { return await analyze(audioBuffer); } catch (error) { console.warn('Could not detect beats, using default:', DEFAULT_TEMPO); return DEFAULT_TEMPO; } } const tempo = await analyzeWithFallback(audioBuffer); // Returns detected tempo or DEFAULT_TEMPO if detection fails ``` -------------------------------- ### Use Default Tempo Settings with Offset and Duration Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Analyzes a specific portion of the audio buffer using default tempo settings. The offset and duration parameters are used to define the analysis window. ```javascript // Analyze 30 seconds of audio starting at 10 seconds // Still uses default tempo range: 90-180 BPM const tempo = await analyze(audioBuffer, 10, 30); const result = await guess(audioBuffer, 10, 30); ``` -------------------------------- ### Use Default Tempo Settings Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Analyzes audio buffer using the default tempo range (90-180 BPM). No explicit configuration is needed. ```javascript import { analyze, guess } from 'web-audio-beat-detector'; // Uses default range: 90-180 BPM const tempo = await analyze(audioBuffer); const result = await guess(audioBuffer); ``` -------------------------------- ### Analyze Tempo with Custom Settings Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/README.md Shows how to use the analyze function with custom tempo range settings, specifically for electronic music (120-160 BPM). This helps improve accuracy for specific music genres. ```javascript // Use custom tempo range for electronic music const tempo = await analyze(audioBuffer, 0, undefined, { minTempo: 120, maxTempo: 160 }); ``` -------------------------------- ### Configure Tempo Range Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Set minimum and maximum tempo constraints for beat analysis. Useful for genres with specific tempo expectations. ```javascript const tempo = await analyze(audioBuffer, 0, undefined, { minTempo: 100, maxTempo: 160 }); ``` -------------------------------- ### Peak Detection Visualization Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/algorithm.md Illustrates the concept of identifying amplitude peaks in audio data over time. This step is crucial for detecting rhythmic patterns. ```text Audio amplitude over time ▲ │ ╱╲ ╱╲ ╱╲ │ ╱ ╲ ╱ ╲ ╱ ╲ │───┤ │───┤ │───┤ │───→ time │ │ │ │ │ │ │ │ ╱ ╲ ╱ ╲ ╱ ╲ │ ╱ ╲ ╲ ╲ ``` -------------------------------- ### CommonJS Import Pattern Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Import pattern for CommonJS environments. Demonstrates using analyze and handling potential errors with Promises. ```javascript const { analyze, guess } = require('web-audio-beat-detector'); analyze(audioBuffer) .then(tempo => console.log('Tempo:', tempo)) .catch(err => console.error('Error:', err)); ``` -------------------------------- ### Synchronize Animation with Detected Beats Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/guess.md Illustrates how to use the results from guess() to synchronize an animation or other timed events with the detected beat intervals and the first beat offset. ```javascript const result = await guess(audioBuffer); const beatIntervalMs = (60 / result.tempo) * 1000; // Schedule first beat animation let nextBeatTime = result.offset * 1000; // Animate beats at detected intervals setInterval(() => { // Trigger beat animation nextBeatTime += beatIntervalMs; }, beatIntervalMs); ``` -------------------------------- ### analyze() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Detects the tempo of an audio buffer. This function is a thin wrapper that delegates the actual computation to a Web Worker. ```APIDOC ## analyze() ### Description Detects the tempo of an audio buffer. ### Method (Asynchronous function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None - **audioBuffer** (AudioBuffer) - Required - The audio data to analyze. - **offset** (number) - Optional - The starting offset in seconds from where to begin analysis. - **duration** (number) - Optional - The duration in seconds for which to perform analysis. - **tempoSettings** (TempoSettings) - Optional - An object to configure tempo detection, with optional `minTempo` and `maxTempo` properties. ### Request Example ```javascript import { analyze } from 'web-audio-beat-detector'; const audioBuffer = /* ... obtain AudioBuffer ... */; const tempo = await analyze(audioBuffer, 0.5, 10, { minTempo: 60, maxTempo: 180 }); console.log('Detected Tempo:', tempo); ``` ### Response #### Success Response - **tempo** (number) - The detected tempo in beats per minute (BPM). #### Response Example ```json 120 ``` #### Error Handling Rejects with an `Error` if no coherent beat pattern is detected in the audio. ``` -------------------------------- ### Analyze with Custom Tempo Settings Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Performs analysis with a custom tempo range, specifying minimum and maximum tempo values. This allows for more targeted beat detection. ```javascript // Analyze with custom tempo range const result = await analyze(audioBuffer, 0, undefined, { minTempo: 120, maxTempo: 180 }); ``` -------------------------------- ### guess() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/module.md Detects the tempo, rounded BPM, and beat offset of an audio buffer. This function is a thin wrapper that delegates the actual computation to a Web Worker. ```APIDOC ## guess() ### Description Detects the tempo, rounded BPM, and beat offset of an audio buffer. ### Method (Asynchronous function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None - **audioBuffer** (AudioBuffer) - Required - The audio data to analyze. - **offset** (number) - Optional - The starting offset in seconds from where to begin analysis. - **duration** (number) - Optional - The duration in seconds for which to perform analysis. - **tempoSettings** (TempoSettings) - Optional - An object to configure tempo detection, with optional `minTempo` and `maxTempo` properties. ### Request Example ```javascript import { guess } from 'web-audio-beat-detector'; const audioBuffer = /* ... obtain AudioBuffer ... */; const result = await guess(audioBuffer); console.log('Guess Result:', result); ``` ### Response #### Success Response - **bpm** (number) - The detected tempo in beats per minute (BPM). - **tempo** (number) - The detected tempo, potentially rounded. - **offset** (number) - The detected beat offset. #### Response Example ```json { "bpm": 120, "tempo": 120.5, "offset": 0.15 } ``` #### Error Handling Rejects with an `Error` if no coherent beat pattern is detected in the audio. ``` -------------------------------- ### analyze() Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/EXPORTS.md Analyzes an AudioBuffer to detect beats and returns the tempo in beats per minute (BPM). It supports various parameter combinations for flexibility. ```APIDOC ## analyze() [Function] ### Description Analyzes an AudioBuffer to detect beats and returns the tempo in beats per minute (BPM). It supports various parameter combinations for flexibility. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **audioBuffer** (AudioBuffer) - Required - The audio data to analyze. - **offset** (number) - Optional - The starting position in seconds to begin analysis. Defaults to 0. - **duration** (number) - Optional - The duration in seconds to analyze. Defaults to the end of the buffer. - **tempoSettings** (TempoSettings) - Optional - Configuration object for tempo range. ### Returns - **Promise** - A promise that resolves with the detected tempo in BPM. ### Throws - **Error** - Thrown when beat detection fails, typically if the audio data does not contain detectable beats. ### Example ```javascript // Example usage with only the required audioBuffer const tempo = await analyze(audioBuffer); // Example usage with all parameters const tempoWithSettings = await analyze(audioBuffer, 10, 30, { minTempo: 80, maxTempo: 160 }); ``` ### Overloads ```typescript // With all parameters analyze(audioBuffer, offset, duration, tempoSettings) // With offset and duration, default settings analyze(audioBuffer, offset, duration) // With offset, default duration and settings analyze(audioBuffer, offset) // With only audio buffer (full buffer, default settings) analyze(audioBuffer) // With audio buffer and settings (full buffer) analyze(audioBuffer, tempoSettings) ``` ``` -------------------------------- ### Preset Configuration for Rock/Alternative Music Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Applies a tempo range suitable for rock, punk, and alternative music genres. This configuration aims to capture tempos typical in these styles. ```javascript const rockSettings = { minTempo: 100, maxTempo: 140 }; const tempo = await analyze(audioBuffer, 0, undefined, rockSettings); ``` -------------------------------- ### Handling Promise Rejections with Async/Await Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/errors.md Implement robust error handling for beat detection functions using async/await with a try-catch block. This ensures that errors during analysis are caught and logged. ```javascript // Using async/await async function detectBeat(audioBuffer) { try { const result = await guess(audioBuffer); return result; } catch (error) { console.error('Beat detection error:', error.message); throw error; // Re-throw or handle as needed } } ``` -------------------------------- ### Preset Configuration for Ambient/Experimental Music Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md Applies a wide tempo range suitable for ambient, downtempo, classical, and jazz music. This configuration accommodates slower and more varied tempos. ```javascript const ambientSettings = { minTempo: 40, maxTempo: 100 }; const tempo = await analyze(audioBuffer, 0, undefined, ambientSettings); ``` -------------------------------- ### TempoSettings Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/types.md Configuration object that customizes the expected tempo range for beat detection. Allows consumers to constrain the beat detection algorithm to a specific tempo range. ```APIDOC ## TempoSettings ### Description Configuration object that customizes the expected tempo range for beat detection. ### Fields | Field | Type | Required | Default | Description | |---|---|---|---|---| | `minTempo` | `number` | No | `90` | The minimum expected tempo in beats per minute (BPM). Beat detection will not return tempos below this value. Must be a positive number. | | `maxTempo` | `number` | No | `180` | The maximum expected tempo in beats per minute (BPM). Beat detection will not return tempos above this value. Must be a positive number and greater than or equal to `minTempo`. | ### Description The `TempoSettings` interface allows consumers to constrain the beat detection algorithm to a specific tempo range. This is useful when you have prior knowledge about the expected tempo of the audio, or when analyzing audio with unusual characteristics that might produce false positives outside the typical range. The algorithm uses these bounds during peak grouping and scoring to filter out candidate tempos that fall outside the specified range. Tempos detected near the boundaries will be scaled by octave (multiplied or divided by 2) if they would be outside the range. ### Used By - `analyze(audioBuffer, offset?, duration?, tempoSettings?)` - Optional fourth parameter - `guess(audioBuffer, offset?, duration?, tempoSettings?)` - Optional fourth parameter ### Examples ```javascript // Detect only fast music (120-180 BPM) const fastMusicSettings = { minTempo: 120, maxTempo: 180 }; // Detect only slow music (40-100 BPM) const slowMusicSettings = { minTempo: 40, maxTempo: 100 }; // Detect typical pop/dance music (85-130 BPM) const popMusicSettings = { minTempo: 85, maxTempo: 130 }; // Apply settings to analyze const tempo = await analyze(audioBuffer, 0, undefined, fastMusicSettings); // Apply settings to guess const result = await guess(audioBuffer, undefined, undefined, slowMusicSettings); ``` ``` -------------------------------- ### Analyze Audio from Blob URL Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Shows how to analyze audio data directly from a Blob object. The Blob is converted to an ArrayBuffer, decoded into an AudioBuffer, and then processed by the `analyze` function. ```javascript import { analyze } from 'web-audio-beat-detector'; async function analyzeBlob(blob) { const arrayBuffer = await blob.arrayBuffer(); const audioContext = new (window.AudioContext || window.webkitAudioContext)(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); return await analyze(audioBuffer); } ``` -------------------------------- ### Smart Tempo Analysis with Genre Presets Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/configuration.md This function analyzes an audio buffer and applies tempo constraints based on the expected genre. It includes a fallback mechanism to a wider tempo range if the initial analysis fails. ```javascript async function smartAnalyze(audioBuffer, expectedGenre) { const genreSettings = { 'electronic': { minTempo: 120, maxTempo: 160 }, 'pop': { minTempo: 85, maxTempo: 130 }, 'ambient': { minTempo: 40, maxTempo: 100 }, 'rock': { minTempo: 100, maxTempo: 140 } }; const settings = genreSettings[expectedGenre] || { minTempo: 90, maxTempo: 180 }; try { return await analyze(audioBuffer, 0, undefined, settings); } catch (error) { // Fallback to wider range return await analyze(audioBuffer, 0, undefined, { minTempo: 40, maxTempo: 200 }); } } ``` -------------------------------- ### Progressive Enhancement for Music Player with Beat Detection Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/usage-examples.md Enhances a music player with beat detection capabilities if supported by the browser. It analyzes audio to enable beat synchronization, with fallback for unsupported environments. ```javascript import { analyze } from 'web-audio-beat-detector'; class MusicPlayer { async init(audioElement) { this.audioElement = audioElement; // Enhance with beat detection if supported if (this.isBeatDetectionSupported()) { try { const audioBuffer = await this.extractAudioBuffer(); this.tempo = await analyze(audioBuffer); this.enableBeatSynchronization(); } catch (error) { console.log('Beat detection not available:', error.message); // Continue without beat sync } } } isBeatDetectionSupported() { return typeof Worker !== 'undefined' && typeof AudioContext !== 'undefined' && typeof Blob !== 'undefined'; } async extractAudioBuffer() { // Load audio and decode to buffer const response = await fetch(this.audioElement.src); const arrayBuffer = await response.arrayBuffer(); const audioContext = new AudioContext(); return await audioContext.decodeAudioData(arrayBuffer); } enableBeatSynchronization() { // Use tempo for synchronized effects console.log(`Playback synchronized to ${this.tempo} BPM`); } } // Usage: Works even if beat detection fails const player = new MusicPlayer(); await player.init(document.querySelector('audio')); ``` -------------------------------- ### Analyze with Offset, Duration, and Custom Tempo Source: https://github.com/chrisguttandin/web-audio-beat-detector/blob/master/_autodocs/api-reference/analyze.md Combine offset, duration, and custom tempo settings for precise analysis of a specific segment within a custom BPM range. This offers maximum flexibility for varied audio content. ```javascript const tempo = await analyze(audioBuffer, 5, 20, { minTempo: 100, maxTempo: 200 }); ```