Python Analysis API
The analysis functions of the libsonare Python package: tempo, key, beats, chords, sections, rhythm, dynamics, timbre, melody, transcription, and the library version and capability queries. Feature extraction is on Python Feature Extraction API, test signals, reconstruction and conversions on Python Signal and Conversion API, metering and signal helpers on Python Metering and Signal Helpers API, room acoustics on Python Room Acoustics API, and the incremental StreamAnalyzer on Python Streaming API. The Audio class is on Python Audio API. Installation, quick start, and the other API families are on the Python API index.
API Reference
The analysis functions take samples and sample_rate; to call them as methods on loaded audio, see Python Audio API.
Analysis Functions
# Detect the BPM (tempo) of audio samples.
def detect_bpm(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
bpm_min: float | None = None,
bpm_max: float | None = None,
) -> float | None: ...
# Detect the musical key of audio samples.
def detect_key(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
use_hpss: bool = False,
loudness_weighted: bool = False,
chroma_high_pass_hz: float = 80.0,
modes: Sequence[KeyMode] | str | None = None,
profile: KeyProfile | None = None,
genre_hint: GenreHint | None = None,
tuning_cents: float | str = 'auto',
) -> KeyDetection: ...
# Detect beat positions in audio samples.
def detect_beats(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
bpm_min: float | None = None,
bpm_max: float | None = None,
) -> np.ndarray: ...
# Detect onset positions in audio samples.
def detect_onsets(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
n_fft: int = 2048,
hop_length: int = 512,
threshold: float | None = None,
pre_max: int = 1,
post_max: int = 1,
pre_avg: int = 3,
post_avg: int = 4,
delta: float = 0.06,
wait: int = 1,
backtrack: bool = False,
backtrack_range: int = 10,
) -> np.ndarray: ...
# Detect downbeat positions in audio samples as a float32 array of seconds.
def detect_downbeats(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...
# Return ranked musical key candidates for ambiguous material.
def detect_key_candidates(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
use_hpss: bool = False,
loudness_weighted: bool = False,
chroma_high_pass_hz: float = 80.0,
modes: Sequence[KeyMode] | str | None = None,
profile: KeyProfile | None = None,
genre_hint: GenreHint | None = None,
tuning_cents: float | str = 'auto',
) -> list[KeyCandidate]: ...
# Detect a continuous chord/N.C.
def detect_chords(
samples: Sequence[float] | list[float],
sample_rate: int,
min_duration_sec: float = 0.3,
smoothing_window_sec: float = 2.0,
threshold: float = 0.5,
use_triads_only: bool = True,
n_fft: int = 2048,
hop_length: int = 512,
use_beat_sync: bool = True,
use_hmm: bool = True,
hmm_beam_width: int = 24,
use_key_context: bool = False,
key_root: PitchClass = PitchClass.C,
key_mode: KeyMode = 'major',
detect_inversions: bool = False,
chroma_method: ChordChromaMethod = 'cqt',
tuning_cents: float | str = 'auto',
) -> ChordAnalysisResult: ...
# Run full audio analysis on samples.
def analyze(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
n_fft: int = 2048,
hop_length: int = 512,
bpm_min: float | None = None,
bpm_max: float | None = None,
start_bpm: float = 120.0,
use_triads_only: bool = True,
use_hpss: bool = False,
chroma_high_pass_hz: float = 80.0,
use_bass_weighted: bool = True,
chroma_hop_multiplier: int = 4,
use_chord_hmm: bool = True,
use_chord_key_context: bool = False,
chord_hmm_beam_width: int = 24,
detect_chord_inversions: bool = False,
adaptive_tempo: bool = False,
tempo_update_interval_beats: int = 8,
compute_tempo_curve: bool = False,
meter_candidate_numerators: Sequence[int] | None = None,
meter_denominator: int = 4,
tuning_cents: float | str = 'auto',
on_progress: ProgressCallback | None = None,
cancel: CancelCallback | None = None,
) -> AnalysisResult: ...
# Transcribe mono audio into MIDI events on a constant-tempo grid.
def transcribe(
samples: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
*,
tempo_bpm: float | None = None,
polyphonic: bool = False,
reference_hz: float | str | None = None,
f0_min_hz: float | None = None,
f0_max_hz: float | None = None,
min_note_ms: float | None = None,
segmentation_threshold_cents: float | None = None,
velocity_floor_db: float | None = None,
fixed_velocity: int | None = None,
group: int = 0,
channel: int = 0,
max_polyphony: int | None = None,
min_frame_peak_ratio: float | None = None,
min_ridge_peak_ratio: float | None = None,
reattack_ratio: float | None = None,
min_note_division: int | None = None,
monophonic_model: Literal['segments', 'singing'] | None = None,
) -> TranscribeResult: ...
# Analyze BPM with confidence, candidates, autocorrelation, and tempogram.
def analyze_bpm(
samples: Sequence[float] | list[float],
sample_rate: int,
bpm_min: float | None = None,
bpm_max: float | None = None,
n_fft: int = 2048,
hop_length: int = 512,
max_candidates: int = 5,
) -> BpmAnalysisResult: ...
# Estimate meter from beat-level observations, without re-analyzing audio.
def estimate_meter(
observations: BeatObservations,
*,
candidate_numerators: Sequence[int] | None = None,
denominator: int = 4,
downbeat_weight: float = 1.0,
measure_weight: float = 0.5,
subdivision_weight: float = 0.15,
compound_subdivision_threshold: float = 0.5,
) -> MeterEstimate: ...
# Detect chords and label them relative to a key.
def chord_functional_analysis(
samples: Sequence[float] | list[float],
sample_rate: int,
key_root: PitchClass,
key_mode: KeyMode = 'major',
min_duration_sec: float = 0.3,
smoothing_window_sec: float = 2.0,
threshold: float = 0.5,
use_triads_only: bool = True,
n_fft: int = 2048,
hop_length: int = 512,
use_beat_sync: bool = True,
use_hmm: bool = True,
hmm_beam_width: int = 24,
use_key_context: bool = False,
detect_inversions: bool = False,
chroma_method: ChordChromaMethod = 'cqt',
tuning_cents: float | str = 'auto',
) -> list[FunctionalChord]: ...
# Label chords that are already known with their harmonic function in a key.
def chord_functions(
chords: ChordAnalysisResult | Sequence[Chord],
key: Key | Mapping[str, object] | tuple[PitchClass, KeyMode],
) -> list[FunctionalChord]: ...
# Convert an analysis key :data:`KeyMode` token into the ``mode`` of a key annotation.
def key_mode_from_analysis(mode: KeyMode) -> ProjectKeyMode: ...
# Convert an analysis :class:`Chord` into the fields of a chord annotation.
def chord_symbol_from_analysis(chord: Chord) -> dict[str, object]: ...
# Analyze rhythm primitives without generating a summary report.
def analyze_rhythm(
samples: Sequence[float] | list[float],
sample_rate: int,
bpm_min: float | None = None,
bpm_max: float | None = None,
start_bpm: float = 120.0,
n_fft: int = 2048,
hop_length: int = 512,
) -> RhythmResult: ...
# Analyze dynamics and loudness primitives.
def analyze_dynamics(
samples: Sequence[float] | list[float],
sample_rate: int,
window_sec: float = 0.4,
hop_length: int = 512,
compression_threshold_db: float = 6.0,
) -> DynamicsResult: ...
# Analyze timbre and spectral-shape primitives.
def analyze_timbre(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_mfcc: int = 13,
window_sec: float = 0.5,
) -> TimbreResult: ...
# Detect song-structure sections (intro/verse/chorus/...) and the form they spell.
def analyze_sections(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
min_section_sec: float = 4.0,
threshold: float | None = None,
) -> SectionAnalysis: ...
# Detect structural boundaries and return the novelty curve behind them.
def detect_boundaries(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
n_fft: int = 2048,
hop_length: int = 512,
kernel_size: int = 64,
threshold: float = 0.3,
absolute_threshold: float = 0.005,
n_mfcc: int = 13,
n_chroma: int = 12,
peak_distance_sec: float = 2.0,
reference_window_sec: float = 60.0,
use_mfcc: bool = True,
use_chroma: bool = True,
) -> BoundaryResult: ...
# Extract the melody contour from monophonic audio.
def analyze_melody(
samples: Sequence[float] | list[float],
sample_rate: int,
f0_min_hz: float = 65.0,
f0_max_hz: float = 2093.0,
frame_length: int = 2048,
hop_length: int = 256,
threshold: float = 0.1,
use_pyin: bool = False,
center: bool = True,
) -> MelodyResult: ...
# Return the libsonare version string.
def version() -> str: ...
# Return the realtime voice-changer ABI version.
def voice_changer_abi_version() -> int | None: ...
# Map a voice-character preset enum ordinal to its canonical id string.
def voice_character_preset_id(ordinal: int) -> str | None: ...
# Return the canonical (normalised) config for a built-in preset.
def realtime_voice_changer_preset_config(preset: VoicePresetId) -> RealtimeVoiceChangerConfig: ...
# Return the realtime engine ABI version used for binding compatibility checks.
def engine_abi_version() -> int: ...
# Return the project C ABI version of the loaded native library.
def project_abi_version() -> int | None: ...
# Return the native library's build, platform, decoder and encoder capabilities.
def capabilities() -> Capabilities: ...AnalysisResult.dynamics and analyze_dynamics() may have None for dynamic_range_db and crest_factor when they were not measured. Check before formatting or using either value:
dynamics = sonare.analyze_dynamics(audio.data, audio.sample_rate)
if dynamics.dynamic_range_db is not None:
print(f"Dynamic range: {dynamics.dynamic_range_db:.1f} dB")
if dynamics.crest_factor is not None:
print(f"Crest factor: {dynamics.crest_factor:.2f}")| Function | Description |
|---|---|
detect_bpm | Tempo in BPM |
detect_key | A Key (root, mode, confidence) plus tuning_cents, the tuning offset in cents its chroma was built with; the default "auto" measures it, tuning_cents=0 reads at A440. detect_key_candidates takes the same options |
detect_beats | Beat timestamps (seconds) |
detect_onsets | Onset timestamps (seconds) |
detect_downbeats | Downbeat timestamps (seconds) |
detect_key_candidates | Ranked key candidates with correlation. profile (a KeyProfile or its name) pins the profile family and outranks genre_hint; leave it None and the genre hint, or the chroma under the default "auto" hint, chooses. tuning_cents is as for detect_key |
detect_chords | Chord segments over time plus the tuning_cents used; frames below the detection threshold are explicit N.C. intervals |
analyze | All-in-one analysis: BPM and its candidates, key, time signature and its candidates, beats, chords (each with roman_numeral relative to the detected key), sections, timbre, dynamics, rhythm, melody, form |
transcribe | Mono audio to MIDI events on a constant-tempo PPQ grid; returns events, note_count, tempo_bpm, and the tuning_cents it used |
analyze_bpm | BPM with top candidates; candidates[0] is the chosen tempo and the rest follow by vote share |
estimate_meter | Meter and accent grouping scored over a beat series you already have — no audio, no re-analysis |
chord_functional_analysis | Detects chords, then returns the timed entries (every Chord field) with roman_numeral ("I", "V7", "vi", ...) and function ("tonic", "subdominant", "dominant", "chromatic", "none") added |
chord_functions | Labels chords you already have in key, without re-detecting. chords is a detect_chords result or its chords list; key is a Key, a {"root": ..., "mode": ...} mapping, or a (root, mode) pair |
key_mode_from_analysis | Converts an analysis key mode token (KeyMode) into the mode a Project.annotate_keys entry takes |
chord_symbol_from_analysis | Converts an analysis Chord into the fields Project.annotate_chords reads (root_pc, quality, extensions, plus slash_bass_pc for a slash chord). Spread it into an entry once you add the PPQ span; times are not converted |
analyze_rhythm | Syncopation, groove type, regularity |
analyze_dynamics | Dynamic range, loudness range, crest factor |
analyze_timbre | Brightness, warmth, density, roughness, complexity, plus per-window timbre_over_time |
analyze_sections | Song-structure sections (intro/verse/chorus/...) |
detect_boundaries | Structural transitions plus the novelty_curve they were picked from, and the grid both live on. threshold is measured against the largest novelty within reference_window_sec seconds of a peak (0 disables it). Reach for it when you want to apply your own threshold rather than take analyze_sections' labeled spans |
analyze_melody | Monophonic melody contour (YIN) |
version | Library version |
voice_changer_abi_version | ABI version of the realtime voice-changer POD config; separate from preset JSON schemaVersion |
voice_character_preset_id | Canonical voice-character preset ID for an integer ordinal; unknown ordinals return None |
realtime_voice_changer_preset_config | Resolved flat POD config for a built-in voice preset, without JSON parsing |
engine_abi_version | ABI version of the realtime engine interface |
project_abi_version | ABI version of the project/editing API used by Project serialization, bounce, and realtime clip exchange |
capabilities | Frozen record of the loaded build: version, abi, platform, features, decode, simd and hardware_concurrency (for example capabilities().features.ffmpeg for FFmpeg decoding) |
transcribe(...)
sonare.transcribe converts mono audio into note events on a constant-tempo PPQ grid. Pass tempo_bpm to choose the grid, or omit it to detect the tempo. The returned TranscribeResult contains events, note_count, the tempo_bpm used, and the tuning_cents used; it does not install a project tempo map. Pass reference_hz="auto" to measure the recording's tuning first; result.tuning_cents reports the value used.
result = sonare.transcribe(
samples,
sample_rate,
tempo_bpm=120.0,
polyphonic=True,
)
print(result.note_count, result.tempo_bpm)
project.set_midi_events(clip_id, result.events)The polyphonic tracker takes max_polyphony (default 10), min_frame_peak_ratio (0.20), min_ridge_peak_ratio (0.10) and reattack_ratio (above 1; omitted means no re-attack split); the shortest note is min_note_ms or, as a note value, min_note_division (not both). The monophonic path refuses the four polyphonic limits by name. See Audio to MIDI.
velocity_floor_db only sets the level that maps to velocity 1. A note more than 36 dB under the take's loudest notes, or under -80 dBFS, is dropped regardless.
Use project.transcribe_to_clip(clip_id, samples, sample_rate, ...) when the events should follow a project's tempo map; it takes the same options as transcribe minus tempo_bpm and returns an int.
analyze_sections(...), analyze_melody(...), cqt(...) and vqt(...) have no Audio method; pass audio.data and audio.sample_rate to them.
In Python, analyze(...) calls sonare_analyze_json and returns the all-in-one AnalysisResult: BPM and ranked BPM hypotheses, key, time signature and its candidates, beats (Beat records with time_sec and a raw strength), chords with roman_numeral labels relative to the detected key, sections, timbre, dynamics, rhythm, melody, and form. The focused functions above remain useful when you want a single facet, parameterized/targeted analysis, or to avoid recomputing the whole result. (Acoustic/room metrics are separate — see estimate_room and the room helpers; they are not part of AnalysisResult.)
keys = sonare.detect_key_candidates(
audio.data,
audio.sample_rate,
modes=["major", "minor"],
profile="krumhanslSchmuckler",
)
chords = sonare.detect_chords(
audio.data,
audio.sample_rate,
use_hmm=True,
use_key_context=True,
key_root=keys[0].key.root,
key_mode=keys[0].key.mode, # a Mode
chroma_method="nnls",
)
sections = sonare.analyze_sections(audio.data, audio.sample_rate)analyze() options
analyze(...) takes the whole analyzer configuration as keyword arguments: n_fft=2048, hop_length=512, bpm_min=None, bpm_max=None (the library's own tempo range), start_bpm=120.0, use_triads_only=True, use_hpss=False, chroma_high_pass_hz=80.0, use_bass_weighted=True, chroma_hop_multiplier=4, use_chord_hmm=True, use_chord_key_context=False, chord_hmm_beam_width=24, detect_chord_inversions=False, adaptive_tempo=False, tempo_update_interval_beats=8, compute_tempo_curve=False, meter_candidate_numerators=None, meter_denominator=4, and tuning_cents="auto", plus the on_progress and cancel callbacks described below.
n_fft is a window length in samples at 22050 Hz and is rescaled to the input rate (hop_length stays in samples of the input); the tempo, beat, onset, key, rhythm, chord and timbre analyzers read it the same way, so a window spans the same time at 44100 Hz or 48000 Hz.
tuning_cents is the recording's tuning offset in cents. It must be in [-50, 50); the default "auto" measures it from the audio, and 0 is concert A440. The same keyword is available on detect_chords(...), chord_functional_analysis(...) and detect_key(...), and shifts the chroma used for key, chords, and sections. The value used, given or measured, comes back as AnalysisResult.tuning_cents, ChordAnalysisResult.tuning_cents, or KeyDetection.tuning_cents. estimate_tuning(...) and pitch_tuning(...) return the same offset at 12 bins per octave. tuning_to_reference_hz and reference_hz_to_tuning convert between that unit and a reference pitch in Hz (a4_hz defaults to 440.0).
Three of these are worth singling out:
meter_candidate_numeratorsdefaults to(3, 4, 6), the native candidate set. An odd meter is reported only if its numerator was among the candidates. At most 16 entries, each in[2, 32]; widening the set does not force a wider meter.meter_denominator(a power of two in[1, 32]) is the beat unit reported for the detected meter.analyze(...)has the audio, so it still reports8on its own when it resolves a compound meter.compute_tempo_curve=Truefillsbeat_local_bpm; it is off by default because it adds an output rather than improving the analysis. Beat tracking holds one fixed tempo prior unlessadaptive_tempo=Trueis also set, so measuring a tempo that actually moves needs both.
Reading the result
key.confidenceis a softmax over the profile correlations of every candidate that was scored: it lies in[0, 1)and the candidates' confidences sum to 1, so a share of 24 candidates cannot reach 1, and a relative major and minor that split the evidence each report about half. It says how decisively the chroma picked one candidate out of the set — not how often that pick is right. Nothing here is calibrated against annotated recordings, so a pipeline that branches on it has to choose its own threshold against its own material.beatsis the beat series (Beatrecords withtime_secandstrength) anddownbeatsis the subset that starts a bar, alsoBeatrecords.downbeat_phaseis the meter estimator's own phase (which beat of the first bar the analysis starts on) and can disagree with the first entry ofdownbeatsonce downbeats are refined from chord and low-frequency evidence.Beat.strengthandbeat_observations.accentare different measurements.Beat.strengthis the raw onset-envelope value in the single frame at the beat.accentis the maximum 5 ms RMS near its strongest attack, in linear units.beat_observationsalso carrieshas_attack,low_frequency_energy,subdivision_accent, andchord_change. An empty optional stream indicates unmeasured evidence. Emptyhas_attacktreats every beat as attacked.beat_local_bpmis the smoothed local tempo at each beat, parallel tobeats. It is empty unlesscompute_tempo_curvewas set, and empty regardless when fewer than two beats were detected, since a tempo is a property of the interval between two beats. The final entry repeats the tempo of the interval leading into the last beat. Do not read a single number out of it as the global tempo — on material whose tempo moves it departs frombpmby design.
Scoring a meter over beats you already have
estimate_meter(observations, ...) scores a caller-supplied BeatObservations record. Pass AnalysisResult.beat_observations to re-score an existing analysis without running the audio pipeline again. See Meter and grouping for the concept.
result = sonare.analyze(audio.data, audio.sample_rate)
obs = result.beat_observations
if obs is not None:
meter = sonare.estimate_meter(obs, candidate_numerators=(3, 4, 5, 6, 7))
if meter.searched:
print(meter.time_signature.numerator, meter.grouping) # e.g. 7 [3, 2, 2]
print(meter.unobserved_beats.tolist()) # masked beats excluded from scoringKeyword options are candidate_numerators (default (3, 4, 6)), denominator=4, downbeat_weight=1.0, measure_weight=0.5, subdivision_weight=0.15, and compound_subdivision_threshold=0.5. Two things decide whether the answer means anything:
- The default candidate set is
{3, 4, 6}, so an odd meter comes back only if you asked for its numerator. searchedisFalsewhen the beat series was shorter than eight beats. Every other field then carries a fixed fallback rather than a result — including the confidence, so a short span's answer must not be read as a detection.
grouping reports how the bar divides into accent groups of two and three beats and always sums to the reported numerator, so a seven comes back as [3, 2, 2]. Use the grouping to tell a compound bar from a simple one: whether a beat divides into three is measured from energy between the beats, which per-beat accents do not carry, so this path reports denominator as requested. candidate_scores is parallel to the numerators you requested while candidates is ordered by descending support — pair a score with a numerator through your request list, never through candidates. Scores are standardized and signed, grow with the square root of the number of beats scored, and are comparable only within one result.
Chord qualities
Chord.quality is one of the strings listed under Types. Some of them are anagrams of each other and no chromagram can separate the pair: a major6 spells the minor7 a minor third below, a minor6 the halfDim7 below it, and a dominant7Sus4 the sus2Add4 a fourth above. The established reading stays the default in each pair, and only bass evidence promotes the sixth.
For long files, analyze(...) accepts an on_progress=(progress, stage) callback and a cancel callback (a true return raises SonareError with ErrorCode.CANCELLED). It mirrors the mastering progress callbacks:
def on_step(progress: float, stage: str) -> None:
print(f"{progress:5.1%} {stage}")
result = sonare.analyze(audio.data, audio.sample_rate, on_progress=on_step)detect_chords(...) and chord_functional_analysis(...) accept tuning_cents in the same unit as analyze(...), and measure it by default. To label chords with Roman numerals relative to a key, use chord_functional_analysis(...). It detects chords with the same algorithm as detect_chords(...), then returns the timed entries with roman_numeral and function added, so there is no separate list to keep in step. When you already hold the chords, chord_functions(...) labels them without detecting again:
labelled = sonare.chord_functional_analysis(
audio.data,
audio.sample_rate,
key_root=keys[0].key.root,
key_mode=keys[0].key.mode,
use_key_context=True,
)
print([(c.start_sec, c.roman_numeral, c.function) for c in labelled]) # e.g. [(0.0, 'I', 'tonic'), ...]
labelled = sonare.chord_functions(chords, keys[0].key)