Krumhansl-Schmuckler Key Profiler — User Guide

Music key detection: implements the Krumhansl-Schmuckler algorithm for automatic key identification from audio signals using correlation with psychological key profiles.

Author: Shai Cohen Affiliation: Department of Music, Bar-Ilan University, Israel Version: 1.0 (2025) License: MIT License Repo: https://github.com/ShaiCohen-ops/Praat-plugin_AudioTools
Contents:

What this does

This script implements the Krumhansl-Schmuckler key-finding algorithm — a psychological model of key perception that correlates audio pitch-class distributions with empirically-derived key profiles. Process: (1) Spectral analysis: Extract spectral peaks from sliding windows. (2) Chroma vector construction: Build 12-dimensional pitch-class distribution (C, C#, D, ..., B). (3) Profile correlation: Compute Pearson correlation between audio chroma and 24 key profiles (12 major, 12 minor). (4) Key identification: Select key with highest correlation as detected key. Result: Automatic key detection with confidence scores and visualizations.

Key Features:

What is the Krumhansl-Schmuckler algorithm? Traditional key detection: Manual score analysis, expert listening. Computational key detection: Mathematical analysis of pitch distributions. Psychological foundation: Based on Carol Krumhansl's research on tonal hierarchies and key perception (1982, 1990). Advantages: (1) Psychologically valid: Matches human perception studies. (2) Robust: Works with various audio qualities. (3) Quantitative: Provides confidence scores. (4) Visual: Clear graphical output. (5) Adaptable: Parameters adjustable for different music styles. Use cases: Music analysis (key identification), musicology research, music information retrieval, DJ software (key matching), music education (ear training), audio processing (key-aware effects).

Technical Implementation: (1) Preprocessing: Optional downsampling for speed, duration validation. (2) Window extraction: Sliding window analysis (Hanning window). (3) Spectral analysis: FFT, peak detection (local maxima). (4) Harmonic filtering: Remove duplicate harmonics based on frequency ratios. (5) Chroma accumulation: Convert frequencies to pitch classes, accumulate across windows. (6) Normalization: Create normalized chroma vector (sum = 1). (7) Correlation calculation: Pearson correlation with 24 key profiles. (8) Result selection: Find maximum correlation, compute confidence. (9) Visualization: Draw chromagram and correlation profile. (10) Output: Text results with top candidates.

Quick start

  1. In Praat, select exactly one Sound object (mono or stereo).
  2. Run script… → Krumhansl_Schmuckler_Key_Profiler.praat.
  3. Set Frequency Range (min: 60 Hz, max: 1500 Hz recommended).
  4. Adjust Window Settings (size: 0.5s, step: 0.25s typical).
  5. Enable Remove harmonic duplicates for cleaner analysis.
  6. Enable Use downsampling for faster processing on long files.
  7. Set Minimum confidence threshold (0.2 typical).
  8. Enable Show full correlation profile for detailed view.
  9. Click OK — analysis runs, results displayed graphically and textually.
Quick tip: For Western tonal music, use default parameters. For polyphonic music (orchestral, choir), increase window size (1.0-2.0s). For monophonic/piano, smaller windows work well (0.3-0.5s). Enable harmonic duplicate removal to focus on fundamental pitches (reduces overtone influence). Use downsampling for files > 30 seconds (speeds processing 10x). Check confidence score (r-value): >0.7 = high confidence, 0.4-0.7 = moderate, <0.4 = low/ambiguous. The chromagram visualization shows which pitch classes are strongest (green = tonic). Full correlation profile shows all 24 key correlations (helps identify ambiguous cases).
Important: TONAL MUSIC REQUIRED — algorithm works best with tonal Western music (classical, pop, jazz). Atonal/12-tone/serial music will produce low confidence. Modulating music (key changes) yields ambiguous results — consider analyzing sections separately. Very short audio (< 5 seconds) may be insufficient for reliable detection. Very noisy/poor quality audio reduces accuracy. Non-equal temperament (historical tunings) may affect results. Frequency range critical — ensure fundamental frequencies fall within min/max range (e.g., bass below 60Hz missed). Window size > audio duration causes error. Results are statistical estimates not absolute truths — use musical knowledge to interpret.

Algorithm Theory

The Krumhansl-Schmuckler Key Profiles

🎵 Psychological Tonal Hierarchies

Empirical foundation: Based on probe-tone experiments (Krumhansl & Kessler, 1982)

Methodology: Listeners rated how well tones fit after tonal context

Result: 12-dimensional weight vectors for each key

C Major Profile:

C Major weights (Krumhansl, 1990): C: 6.35 (tonic - strongest) C#: 2.23 D: 3.48 D#: 2.33 E: 4.38 (mediant - strong) F: 4.09 (subdominant - strong) F#: 2.52 G: 5.19 (dominant - very strong) G#: 2.39 A: 3.66 A#: 2.29 B: 2.88 (leading tone - moderate) Interpretation: Tonal hierarchy from strongest (tonic) to weakest (non-diatonic)

C Minor Profile:

C Minor weights: C: 6.33 (tonic) C#: 2.68 D: 3.52 D#: 5.38 (minor third - characteristic) E: 2.60 F: 3.53 F#: 2.54 G: 4.75 (dominant) G#: 3.98 (minor sixth - characteristic) A: 2.69 A#: 3.34 (minor seventh) B: 3.17 Note: Raised ^6 and ^7 in minor (harmonic/melodic minor) not modeled separately

Mathematical Processing Pipeline

🔢 From Audio to Key Decision

Step 1: Chroma Vector Extraction

FOR each analysis window: 1. Compute spectrum (FFT) 2. Detect spectral peaks (local maxima) 3. Filter harmonics (optional) 4. Convert frequencies → MIDI → pitch classes (0-11) 5. Accumulate power per pitch class RESULT: 12-dimensional vector C = [c₀, c₁, ..., c₁₁] where cᵢ = total power in pitch class i

Step 2: Chroma Normalization

total = Σ cᵢ (i = 0 to 11) normalized_chroma[i] = cᵢ / total PROPERTIES: Σ normalized_chroma[i] = 1 Each value ∈ [0,1] Represents relative importance of each pitch class

Step 3: Profile Correlation

For each key k (0-23): Let Pₖ = key profile vector (12 values) Let C = audio chroma vector Compute Pearson correlation rₖ: nΣ(CᵢPₖᵢ) - ΣCᵢ ΣPₖᵢ rₖ = ----------------------------------------- √[nΣCᵢ² - (ΣCᵢ)²] √[nΣPₖᵢ² - (ΣPₖᵢ)²] where n = 12 (dimensionality)

Step 4: Key Selection

best_key = argmaxₖ rₖ best_correlation = max(rₖ) Confidence interpretation: r > 0.7: Very high confidence 0.5 < r ≤ 0.7: Good confidence 0.3 < r ≤ 0.5: Moderate confidence r ≤ 0.3: Low confidence (ambiguous/atonal)

Profile Rotation for All Keys

🔄 Generating 24 Key Profiles

C Major profile is canonical major: P_maj = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]

C Minor profile is canonical minor: P_min = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]

For key with root r (0=C, 1=C#, ..., 11=B):

Major key r: profile[i] = P_maj[(i - r) mod 12] Minor key r: profile[i] = P_min[(i - r) mod 12] EXAMPLE: G Major (r = 7): G (pitch class 7) gets weight 6.35 (tonic) G# (8) gets weight 2.23 A (9) gets weight 3.48 etc.

Result: 24 profiles (12 major × 12 minor) covering all keys

Spectral Analysis Details

🔬 Peak Detection & Harmonic Filtering

Peak detection algorithm:

FOR each frequency bin i (excluding edges): power[i] = √(re[i]² + im[i]²) IF power[i] > power[i-1] AND power[i] > power[i+1] AND power[i] > threshold THEN register as spectral peak Threshold: 0.0001 (prevents noise peaks) Max peaks per frame: 8 (configurable)

Harmonic duplicate removal:

FOR each peak pair (i, j): ratio = freq[i] / freq[j] nearest_harmonic = round(ratio) IF nearest_harmonic ≥ 2: cents_deviation = |1200 × log₂(ratio / nearest_harmonic)| IF cents_deviation < tolerance (default: 50 cents): Keep only stronger peak (higher power) Rationale: Remove harmonics to focus on fundamental frequencies

Frequency to pitch class conversion:

MIDI = 69 + 12 × log₂(freq / 440) pitch_class = round(MIDI) mod 12 If pitch_class < 0: add 12

Window-Based Analysis

⏱️ Temporal Integration

Sliding window approach:

Parameters: Window size = 0.5 seconds (configurable) Time step = 0.25 seconds (configurable) Processing: t = 0 WHILE t ≤ (duration - window_size): Extract window: [t, t + window_size] Analyze window → chroma contribution Add to global chroma vector t = t + time_step Advantages: - Captures temporal evolution - Averages over time - Reduces momentary anomalies

Hanning window function:

w[n] = 0.5 × (1 - cos(2πn/(N-1))) for n = 0,...,N-1 Benefits: - Reduces spectral leakage - Smoothes window edges - Standard for audio analysis

Parameters Explained

Analysis Parameters

ParameterDefaultRangeDescription
Min_frequency_Hz6020-500Minimum frequency for analysis
Max_frequency_Hz1500500-5000Maximum frequency for analysis
Harmonic_tolerance_cents5010-100Tolerance for harmonic detection
Remove_harmonic_duplicatesyesyes/noFilter out harmonic multiples

Window Settings

ParameterDefaultRangeDescription
Window_size_seconds0.50.05-5.0Analysis window duration
Time_step_seconds0.250.01-2.0Time between windows
Max_peaks_per_frame81-20Maximum spectral peaks per window

Speed Optimization

ParameterDefaultDescription
Use_downsamplingyesDownsample long files for speed
Target_sample_rate_Hz8000Target rate for downsampling

Display Options

ParameterDefaultDescription
Show_full_correlation_profileyesShow all 24 key correlations
Minimum_confidence_threshold0.2Threshold for confidence warnings

Parameter Guidelines

For different music types:
  • Piano/solo instrument: Window size: 0.3-0.5s, Min freq: 60Hz, Max freq: 2000Hz
  • Orchestral/polyphonic: Window size: 1.0-2.0s, Min freq: 40Hz, Max freq: 1500Hz
  • Pop/rock with bass: Min freq: 40Hz (include bass), Harmonic tolerance: 30 cents
  • Choral music: Window size: 0.5-1.0s, Max peaks: 12-15
  • Short excerpts (<10s): Disable downsampling, smaller time step (0.1s)
  • Noisy recordings: Increase harmonic tolerance (70-100 cents), lower min freq

Output Interpretation

Graphical Output

📊 Understanding the Visualizations

Top section: Key Result

  • Detected Key: Primary result (e.g., "G Major")
  • Confidence: Pearson r-value with interpretation
  • Second choice: Runner-up key with correlation

Middle section: Chromagram

  • 12 bars: One for each pitch class (C to B)
  • Height: Relative strength of that pitch class
  • Green bar: Tonic of detected key
  • Blue bars: Other pitch classes
  • Interpretation: Visual pattern of tonal hierarchy

Bottom section (optional): Full Correlation Profile

  • 24 dots: One for each key (12 major, 12 minor)
  • Height: Correlation strength (r-value)
  • Green dot: Detected key
  • Orange dots: Other keys with r > 0.3
  • Gray dots: Low-correlation keys

Text Output (Info Window)

=== DETECTED KEY: G Major === Correlation: 0.8245 =================================== Top 5 key candidates: 1. G Major (r = 0.8245) 2. D Major (r = 0.7123) 3. E Minor (r = 0.6541) 4. C Major (r = 0.5987) 5. B Minor (r = 0.5432) Analysis complete!

Confidence Interpretation

🎯 What the Correlation Values Mean

Correlation (r)Confidence LevelInterpretation
0.8 - 1.0ExcellentClear, unambiguous key
0.6 - 0.8Very GoodStrong key feeling
0.4 - 0.6GoodModerately clear key
0.2 - 0.4LowAmbiguous or weakly tonal
< 0.2Very LowAtonal or analysis failure

Common Output Patterns

Typical results for different scenarios:
  • Clear major key: High r (>0.7), dominant and mediant strong in chromagram
  • Clear minor key: High r (>0.7), minor third and sixth prominent
  • Modulating music: Moderate r (0.4-0.6), multiple keys with similar correlations
  • Pentatonic music: Moderate r, only 5 pitch classes strong in chromagram
  • Atonal music: Low r (<0.3), flat or random chromagram
  • Ambiguous cases: Close runner-up (difference <0.1 in r-value)

Troubleshooting Output Issues

Problem: "No spectral peaks found" error
Cause: Frequency range doesn't match audio content
Solution: Adjust Min_frequency_Hz and Max_frequency_Hz
Problem: Very low confidence (r < 0.2)
Cause: Audio may be atonal, noisy, or non-Western
Solution: Check if music is tonal Western music
Problem: Wrong key detected
Cause: Relative major/minor confusion, or modulation
Solution: Check runner-up keys, analyze shorter sections
Problem: Processing very slow
Cause: Long file, no downsampling, small time step
Solution: Enable downsampling, increase time step

Applications

Musicological Research

Use case: Analyzing key usage in musical corpora

Workflow: Batch process multiple pieces, collect key statistics

Research questions: Key distributions by composer/period, modulation patterns

Music Information Retrieval

Use case: Automatic metadata generation for music databases

Application: Key-based music organization, playlist generation

Example: DJ software for harmonic mixing (matching compatible keys)

Music Education

Use case: Ear training and key identification practice

Tool: Students analyze excerpts, compare with algorithm

Pedagogical value: Visual feedback on tonal perception

Audio Processing

Use case: Key-aware audio effects and processing

Examples: Key-tuned equalization, harmonic exciters, adaptive filters

Real-time applications: Live performance processing, DJ tools

Music Transcription & Analysis

Use case: Assisting in automatic music transcription

Integration: Key information improves pitch spelling accuracy

Workflow: First detect key, then transcribe with key context

Composition & Production

Use case: Analyzing influence pieces, understanding key relationships

Creative applications: Key-based sample organization, harmonic planning

Production workflow: Ensure consistency in key across project

Practical Examples

🎵 Analyzing a Beethoven Sonata Movement

Goal: Detect primary key and modulations

Settings: Window size: 1.0s, Time step: 0.5s, Frequency range: 40-2000Hz

Method: Analyze whole movement, then sections separately

Results: Primary key: C Minor, Modulation to E♭ Major detected

📊 Batch Analysis of Pop Song Corpus

Goal: Statistical analysis of key preferences in pop music

Settings: Default parameters, enable downsampling for speed

Automation: Script to process folder of songs, export CSV results

Findings: Most common keys: C Major, G Major, D Major (guitar-friendly)

🎧 DJ Harmonic Mixing Assistant

Goal: Determine compatible keys for smooth transitions

Settings: Quick analysis: Window size: 0.3s, downsampling enabled

Camelot wheel mapping: Convert key results to Camelot codes (e.g., 8A = C Minor)

Application: Suggest tracks compatible with current playing key

Limitations & Considerations

Algorithm limitations to be aware of:
  • Equal temperament assumption: Historical tunings may reduce accuracy
  • Western tonal system: Designed for Western common practice period music
  • No chord recognition: Detects key, not individual chords
  • Temporal resolution: Modulations faster than window size may be missed
  • Monophonic bias: Works best with clear tonal center
  • Psychological not acoustic: Based on perception, not acoustic properties
  • Profile rigidity: Fixed profiles don't adapt to style variations

Advanced Techniques

For research and advanced applications:
  • Custom profiles: Modify profile vectors for specific styles
  • Dynamic windowing: Adapt window size based on musical features
  • Multi-profile correlation: Test against multiple profile sets
  • Temporal tracking: Plot key confidence over time for modulation detection
  • Ensemble methods: Combine with other key detection algorithms
  • Mode detection: Extend to modal music (Dorian, Phrygian, etc.)
  • Visualization enhancement: Add circle of fifths display, chord progressions