# BPM & Key Detector - Tempo, Beat Grid, Camelot Key (`freecamp008/bpm-key-detector`) Actor

Detect the BPM, beat grid and musical key of songs from audio or video URLs. Get tempo with confidence, half/double-time alternatives, key and mode in Camelot and Open Key notation, tuning and EBU R128 loudness. Runs on CPU, no external APIs.

- **URL**: https://apify.com/freecamp008/bpm-key-detector.md
- **Developed by:** [Camp8 fr0](https://apify.com/freecamp008) (community)
- **Categories:** AI, For creators, Developer tools
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 track analyzeds

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## BPM & Key Detector: Song Tempo, Beat Grid and Musical Key (Camelot / Open Key)

Find the **BPM (tempo)**, **beat grid** and **musical key** of any song from a URL. Paste links to MP3, WAV, FLAC, OGG, M4A or video files and get the tempo with a confidence score and half/double-time alternatives, the first beat and beat interval for DJ software, the key and mode in standard, **Camelot** and **Open Key** notation, the tuning reference, and EBU R128 loudness (LUFS, loudness range, true peak). All analysis runs inside the Actor with its own signal-processing code and ffmpeg. No Spotify API, no paid audio API, and no AGPL libraries.

### What does BPM & Key Detector do?

- Downloads each audio or video file, decodes it with ffmpeg and resamples it to 22.05 kHz mono
- Computes an **onset strength envelope** (log-mel spectral flux) and a **tempogram** (windowed autocorrelation) to estimate the tempo, with a perceptual tempo prior and an explicit **half-time / double-time decision**
- Tracks the beats with **dynamic programming** (Ellis 2007) and fits a straight beat grid to get a precise BPM (e.g. 127.98 becomes 128 when the grid is tight), the first beat and the beat interval
- Estimates the **tuning** (A4 reference in Hz and cents) from spectral peaks and builds a **harmonic pitch-class profile** (chroma) from 55 Hz to 2 kHz
- Correlates the chroma with 24 rotated **key profiles** (Albrecht & Shanahan by default; Krumhansl-Kessler, Temperley or an ensemble on request) and returns the key, the runner-up and how they relate (relative, parallel, fifth)
- Measures **integrated loudness (LUFS), loudness range (LU), true peak (dBTP)** and sample peak per ITU-R BS.1770 / EBU R128

### Key features

- **BPM detection** with a 0-1 confidence score, the top tempo candidates, half-time and double-time values, and a tempo-stability flag (live drummer vs. quantized)
- **DJ-style BPM range**: fold the tempo into 70-140, 90-180 (drum & bass, dubstep) or another range, like Rekordbox, Serato or Traktor do
- **Beat grid**: first beat, beat interval and beat count; optionally every beat timestamp
- **Key detection** in three notations: `A minor`, Camelot `8A` and Open Key `1m`, with a confidence score and the runner-up key for harmonic mixing
- **Tuning estimate**: detects songs that are not tuned to A = 440 Hz (for example 432 Hz or vinyl rips at the wrong speed)
- **Loudness**: integrated LUFS, LRA and true peak, ready for streaming-loudness checks
- **Any format ffmpeg reads**: MP3, WAV, AIFF, FLAC, OGG, OPUS, M4A/AAC, WMA, and the audio track of MP4, MOV, MKV and WEBM files
- **Section analysis**: skip a long intro with `startSec` and cap long DJ mixes with `maxDurationMinutes`
- **Private and self-contained**: pure JavaScript DSP + ffmpeg inside the container; your audio is not sent to any third-party service
- **HTTP API (Standby mode)**: call it like a REST endpoint and get the analysis in the response

### Use cases

- **DJ library preparation**: BPM, Camelot key and beat grid for harmonic mixing and auto-sync
- **Music catalogs and sync licensing**: tag tracks with tempo, key and loudness for search filters ("120-128 BPM, A minor")
- **Playlist and workout apps**: sort songs by tempo for running cadence, dance classes or fitness programs
- **Producers and remixers**: find the key and tempo of a sample, stem or reference track
- **Music apps and AI pipelines**: features for recommendation, mood or genre models
- **Audio QA**: catch tracks that are off-tuning, too quiet or clipping

### How to use BPM & Key Detector

#### In Apify Console

1. Click **Try for free** or **Start**.
2. Paste one or more **direct links to audio or video files** into *Audio / video URLs*.
3. Optionally pick a **BPM range** (for example *90-180* for drum & bass) and a **Key profile**.
4. Click **Start**. Each track appears in the **BPM & key** table with BPM, key, Camelot, Open Key, confidence scores and loudness.

#### Via the Apify API

```bash
curl -X POST "https://api.apify.com/v2/acts/freecamp008~bpm-key-detector/run-sync-get-dataset-items?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "audioUrls": ["https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg"],
    "bpmRange": "auto",
    "includeBeats": false
  }'
```

Or use the [apify-client](https://docs.apify.com/api/client/js/) for JavaScript or Python.

#### Standby mode (instant HTTP endpoint)

The Actor also runs as a persistent web server. Send the input fields as query parameters (arrays comma-separated) or as a JSON body. The response is `{ "count": n, "items": [...] }`.

```bash
## GET
curl "https://freecamp008--bpm-key-detector.apify.actor/?token=YOUR_API_TOKEN&audioUrls=https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg&bpmRange=90-180"

## POST
curl -X POST "https://freecamp008--bpm-key-detector.apify.actor/?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"audioUrls": ["https://example.com/track.mp3"], "startSec": 30, "includeBeats": true}'
```

**AI agents** can call this Actor and pay per call with **x402** through Apify. No Apify account or subscription is needed: the agent pays for each call.

### Input example

```json
{
  "audioUrls": [
    "https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg",
    "https://raw.githubusercontent.com/librosa/data/main/audio/Kevin_MacLeod_-_Vibe_Ace.hq.ogg"
  ],
  "bpmRange": "auto",
  "keyProfile": "auto",
  "startSec": 0,
  "maxDurationMinutes": 15,
  "includeBeats": false,
  "measureLoudness": true
}
```

| Field | Description | Default |
|---|---|---|
| `audioUrls` | Direct links to audio/video files | required |
| `bpmRange` | `auto`, or fold the BPM into `50-100`, `60-120`, `70-140`, `80-160`, `90-180`, `100-200` | `auto` |
| `keyProfile` | `auto` (Albrecht & Shanahan), `albrecht`, `krumhansl`, `temperley`, `ensemble` | `auto` |
| `startSec` | Skip the first N seconds (long intros) | `0` |
| `maxDurationMinutes` | Analyze and bill at most N minutes per file (1-60) | `15` |
| `includeBeats` | Add every beat timestamp (`tempo.beats`) | `false` |
| `measureLoudness` | Add EBU R128 loudness (LUFS, LRA, true peak) | `true` |

### Output example

One dataset item per file (shortened):

```json
{
  "audioUrl": "https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg",
  "bpm": 136,
  "bpmConfidence": 0.76,
  "key": "D major",
  "keyShort": "D",
  "camelot": "10B",
  "openKey": "3d",
  "keyConfidence": 0.5,
  "durationSec": 25.03,
  "analyzedFromSec": 0,
  "analyzedSec": 25.03,
  "tempo": {
    "bpm": 136,
    "bpmInteger": 136,
    "confidence": 0.76,
    "halfTimeBpm": 68,
    "doubleTimeBpm": 272,
    "candidates": [{ "bpm": 135.8, "score": 0.462 }, { "bpm": 67.9, "score": 0.429 }, { "bpm": 90.2, "score": 0.29 }],
    "stable": true,
    "tempoVariation": 0.023,
    "beatGrid": { "firstBeatSec": 0.023, "beatIntervalSec": 0.4409, "beatCount": 57, "gridBpm": 136.07 }
  },
  "tonality": {
    "key": "D major",
    "tonic": "D",
    "mode": "major",
    "camelot": "10B",
    "openKey": "3d",
    "confidence": 0.5,
    "correlation": 0.878,
    "runnerUp": { "key": "G major", "camelot": "9B", "correlation": 0.788, "relation": "subdominant (fifth below)" },
    "candidates": [{ "key": "D major", "camelot": "10B", "correlation": 0.878 }, { "key": "G major", "camelot": "9B", "correlation": 0.788 }],
    "tuningCents": 5.7,
    "tuningHz": 441.44,
    "chroma": { "C": 0.0599, "C#": 0.0852, "D": 0.1525, "D#": 0.0214, "E": 0.0753, "F": 0.0573, "F#": 0.0936, "G": 0.1361, "G#": 0.0579, "A": 0.1407, "A#": 0.0532, "B": 0.0669 }
  },
  "loudness": { "integratedLufs": -25.5, "loudnessRangeLu": 2.4, "truePeakDbtp": -7.6, "samplePeakDbfs": -8 },
  "format": { "container": "ogg", "codec": "vorbis", "sampleRate": 44100, "channels": 2, "bitRate": 421433 },
  "billedMinutes": 1,
  "processingSec": 3.41,
  "truncated": false,
  "truncatedReason": null
}
```

With `includeBeats: true`, `tempo.beats` lists every beat time in seconds. When a file can't be downloaded or decoded, the Actor returns `{ "audioUrl", "error", "isError": true }` for it, and that item is free. When a file is longer than `maxDurationMinutes` or the run budget, only the beginning is analyzed and the item has `truncated: true`.

### Pricing

This Actor uses **pay-per-event** pricing:

| Event | Price | Per 1,000 |
|---|---|---|
| `track-analyzed`: one successfully analyzed file | $0.002 | **$2 per 1,000 tracks** |
| `audio-minute`: one started minute of analyzed audio (rounded up per file) | $0.0005 | **$0.50 per 1,000 minutes** |

Example: a typical 4-minute song costs $0.002 + 4 × $0.0005 = **$0.004**. 1,000 songs cost about **$4**. Set `maxDurationMinutes` to 3 to cap every track at $0.0035; tempo and key are usually stable after 2-3 minutes.

Failed downloads and unreadable files are not charged. Apify platform usage (compute units) is billed separately. Analysis is light: a 4-minute song needs about 2 seconds of CPU time (roughly 5-10 s of run time at the default 1 GB memory, which gets a quarter of a CPU core). 1 GB is enough for files up to about 45 minutes; use 2 GB for hour-long DJ mixes (peak memory about 0.8 GB).

### FAQ

**How accurate is the BPM?**
We measured it on a 200-track subset of the public GTZAN benchmark (10 genres, GTZAN-Rhythm annotations): **71.5% of tracks within 4% of the annotated tempo, 88% when half/double/triple-time answers also count**. The tempo prior was tuned on half of those tracks; the other half scored 73% / 90%. Most remaining errors are octave choices (reporting 87 instead of 174, for example) and 3:2 confusions in jazz and classical music. Tracks with `bpmConfidence` of 0.5 or higher were right 78% of the time, below 0.5 only 35%. On steady electronic, pop, disco and reggae tracks it is right far more often than on rubato classical music.

**My drum & bass track shows 87 BPM instead of 174. Why?**
Both are valid metrical levels; listeners and DJ tools disagree on which one is "the" tempo. Set **BPM range** to `90-180` (drum & bass, dubstep, footwork) or `70-140` (hip-hop, house, techno), and the result is folded into that range. `halfTimeBpm` and `doubleTimeBpm` are always returned as well.

**How accurate is the key?**
Exact-key accuracy was **64.5% on 169 GTZAN tracks** (MIREX weighted score 72%) and **50-55% on 80 GiantSteps EDM tracks** (MIREX score 60-65%; the shard not used for tuning scored 50%). Most errors are musically close keys: relative major/minor (same Camelot number), parallel major/minor or a fifth away (adjacent Camelot numbers), which still mix harmonically. Tracks with `keyConfidence` of 0.5 or higher were exact 83% of the time on GTZAN. This is in line with classic profile-based key finders. Deep-learning key models score higher on EDM, but they are larger and slower.

**Which audio formats and lengths are supported?**
Anything ffmpeg can read from a URL: MP3, WAV, AIFF, FLAC, OGG/Vorbis, OPUS, M4A/AAC, WMA, and the audio of MP4, MOV, MKV and WEBM videos. Files need at least 5 seconds of audio. Each file is analyzed up to `maxDurationMinutes` (default 15, maximum 60). For DJ mixes or songs with tempo or key changes, the result describes the analyzed section as a whole; use `startSec` and `maxDurationMinutes` to analyze one section.

**Can it analyze Spotify, YouTube or SoundCloud links?**
No. It needs a direct link to the audio file (for example a URL ending in `.mp3`, a podcast enclosure or a file in your own cloud storage). Pages with an embedded player don't work. Only process content you have the right to use.

**Is my audio private? Which libraries does it use?**
Analysis runs entirely inside the Actor container. The tempo, beat and key algorithms are our own JavaScript code (no essentia, no librosa, no AGPL or GPL code), and decoding uses Debian's ffmpeg build (LGPL/GPL, run as a separate program). Audio is not sent to any third-party API, and results are stored only in your Apify storage.

**Is it legal to analyze songs?**
Measuring tempo, key and loudness of audio you own, have licensed or that is openly licensed is generally fine. You are responsible for having the right to download and process the files you submit. The Actor does not store or redistribute your audio.

**What does the confidence score mean?**
`bpmConfidence` combines how prominent the chosen tempo is in the tempogram with how consistently it shows up across the track. `keyConfidence` combines the correlation with the key profile and the margin over the runner-up key. Both are 0-1; treat values below 0.3 as "ambiguous" and check the candidates and runner-up.

# Actor input Schema

## `audioUrls` (type: `array`):

Direct links to music files (MP3, WAV, FLAC, OGG, OPUS, M4A, AAC, AIFF, or the audio track of MP4/WEBM/MOV videos). Each file becomes one result with BPM, beat grid, key and loudness. The link must return the file itself, not a web page with a player.

## `bpmRange` (type: `string`):

<b>Auto</b> picks the most likely tempo level (tuned on a public benchmark). Choose a range to fold the result by octaves into it, the way DJ software does: e.g. <b>90-180</b> for drum & bass or dubstep (174 instead of 87), <b>70-140</b> for hip-hop, house and techno. Half-time and double-time values are always returned too.

## `keyProfile` (type: `string`):

Pitch-class profile used to turn the chroma into a key. <b>Auto</b> (Albrecht & Shanahan) was the most accurate on our pop/rock/EDM/classical test sets. Krumhansl-Kessler and Temperley are the classic alternatives; <b>Ensemble</b> averages all three.

## `startSec` (type: `integer`):

Skip this many seconds at the start of each file (e.g. a long intro without drums). Beat times are still reported relative to the start of the file.

## `maxDurationMinutes` (type: `integer`):

Analyze (and bill) at most this many minutes of each file. 3-5 minutes are plenty for a stable BPM and key; longer DJ mixes are marked <code>truncated: true</code>.

## `includeBeats` (type: `boolean`):

Add <code>tempo.beats</code>: the time (seconds) of every detected beat. The compact beat grid (first beat + interval) is always included.

## `measureLoudness` (type: `boolean`):

Add integrated loudness (LUFS), loudness range (LU), true peak (dBTP) and sample peak (dBFS), measured per ITU-R BS.1770 / EBU R128 on the original channels.

## Actor input object example

```json
{
  "audioUrls": [
    "https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg",
    "https://raw.githubusercontent.com/librosa/data/main/audio/Kevin_MacLeod_-_Vibe_Ace.hq.ogg"
  ],
  "bpmRange": "auto",
  "keyProfile": "auto",
  "startSec": 0,
  "maxDurationMinutes": 15,
  "includeBeats": false,
  "measureLoudness": true
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "audioUrls": [
        "https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("freecamp008/bpm-key-detector").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "audioUrls": ["https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg"] }

# Run the Actor and wait for it to finish
run = client.actor("freecamp008/bpm-key-detector").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "audioUrls": [
    "https://raw.githubusercontent.com/librosa/data/main/audio/admiralbob77_-_Choice_-_Drum-bass.hq.ogg"
  ]
}' |
apify call freecamp008/bpm-key-detector --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,freecamp008/bpm-key-detector"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ihRCRHs1Nf8Eo6a60/builds/onBrrVGqKxpooSgAl/openapi.json
