Python Analysis Types
The result records returned by the analysis functions on Python Analysis API, the feature, pitch and loudness functions on Python Feature Extraction API and Python Signal and Conversion API, and the metering functions on Python Metering and Signal Helpers API. Every record is a frozen dataclass; the matrix layout rule is on Python Types. Records of the incremental StreamAnalyzer are on Python Streaming Types, and the effects and note-editing records on Python Effects Types.
Key and time signature
Key.root is a PitchClass. Key.confidence is a share of the model's belief that this key is the answer, in [0, 1): a softmax over the profile correlations of every candidate that was scored, so it falls as the runner-up closes in, and two keys that split the evidence (a relative major and minor, typically) each report about half. It is not a measured accuracy; a pipeline that branches on it has to choose its own threshold against its own material.
detect_key returns a KeyDetection, a Key that also carries tuning_cents, the tuning the chroma was built with: the value given, or the measured one under tuning_cents="auto". detect_key_candidates returns KeyCandidate records whose correlation is the raw correlation of the chroma with that key's profile. Key.name is the key spelled out ("C major", "A minor"); Key.short_name is "C" for major, "Cm" for minor and the long form otherwise.
# Detected musical key.
@dataclass(frozen=True, slots=True)
class Key:
root: PitchClass
mode: KeyMode
confidence: float
# Key spelled out, e.g.
@property
def name(self) -> str: ...
# Compact key spelling: ``"C"`` for major, ``"Cm"`` for minor, the long form otherwise.
@property
def short_name(self) -> str: ...
# A detected key and the tuning its chroma was built with.
@dataclass(frozen=True, slots=True)
class KeyDetection(Key):
tuning_cents: float = 0.0
root: PitchClass
mode: KeyMode
confidence: float
# Key spelled out, e.g.
@property
def name(self) -> str: ...
# Compact key spelling: ``"C"`` for major, ``"Cm"`` for minor, the long form otherwise.
@property
def short_name(self) -> str: ...
# Key candidate with raw profile correlation.
@dataclass(frozen=True, slots=True)
class KeyCandidate:
key: Key
correlation: float
# Detected time signature.
@dataclass(frozen=True, slots=True)
class TimeSignature:
numerator: int
denominator: int
confidence: floatmode takes a KeyMode token and the key profile a KeyProfile token; both are listed on Python Tokens and Aliases.
TimeSignature.numerator is beats per bar and denominator the note value of one beat (4 is a quarter note); confidence is the belief in this meter over the other candidates, in [0, 1].
Tempo, beats and meter
Beat.strength is the raw onset-envelope value in one frame at the beat. For accent scoring use AnalysisResult.beat_observations.accent, the maximum 5 ms RMS near the strongest attack around each beat, in linear units.
BeatObservations holds the evidence used by meter and downbeat scoring. accent, has_attack, low_frequency_energy, and chord_change are indexed by beat. subdivision_accent has one value per interval. An empty optional stream indicates unmeasured evidence. A zero indicates measured silence. Empty has_attack treats every beat as attacked. Empty low_frequency_energy disables masked-beat scoring. Chord analysis fills chord_change.
BpmAnalysisResult is the return type of analyze_bpm. confidence is the winning tempo cluster's vote share in [0, 1] within bpm_min to bpm_max (60 to 200 by default), searched at the input rate; analyze searches at 22050 Hz, so its bpm_confidence can differ. candidates opens with the chosen tempo (candidates[0].bpm == bpm) and the other histogram bins follow by descending vote share. AnalysisBpmCandidate, the candidate type inside analyze, adds relation to the chosen tempo: "primary", "half", "double" or "other".
estimate_meter returns a MeterEstimate:
searchedisFalsewhen the beat series was too short to score any candidate; every other field then carries a fixed fallback rather than a detection (the confidence reported with it is 0). Read it before treating a short span's answer as a result.candidate_scoresis parallel to the numerators you requested, in request order, whilecandidatesis ordered by descending support. Pair a score with a numerator through the request list, never throughcandidates.- A
candidate_scoresentry is standardized and signed: zero is the level a numerator reaches on beats carrying no meter, so a negative entry means less support than noise would produce. Only the ordering and the gaps carry meaning, and only within one result: a score grows with the square root of the beat count, so the same meter over twice the beats scores about 1.41 times as high. groupingis anint32array of how the bar divides, in beats per accent group:[3, 2, 2]is the 7/8 notated as 3+2+2,[2, 2]an ordinary four. It always sums totime_signature.numerator; a single entry means no internal division was resolved.time_signature.confidenceis derived from the margin over the runner-up, while acandidatesentry'sconfidenceis that candidate's share of the summed support. The two are not comparable.downbeat_phaseis the beat index the first bar starts on, in[0, time_signature.numerator).unobserved_beatsis an int32 array of ascending zero-based indices for masked beats excluded from scoring. It is empty when no per-beat energy was supplied.
# A tempo candidate with its confidence.
@dataclass(frozen=True, slots=True)
class BpmCandidate:
bpm: float
confidence: float
# A tempo candidate of :func:`analyze`, with its relation to the chosen tempo.
@dataclass(frozen=True, slots=True)
class AnalysisBpmCandidate(BpmCandidate):
relation: BpmCandidateRelation
bpm: float
confidence: float
# Detailed BPM analysis result.
@dataclass(frozen=True, slots=True, eq=False)
class BpmAnalysisResult:
bpm: float | None
confidence: float
candidates: list[BpmCandidate]
autocorrelation: npt.NDArray[np.float32]
tempogram: npt.NDArray[np.float32]
# Beat event.
@dataclass(frozen=True, slots=True)
class Beat:
time_sec: float
strength: float
# Beat-level evidence behind the downbeat and meter decisions.
@dataclass(frozen=True, slots=True, eq=False)
class BeatObservations:
accent: npt.NDArray[np.float32] = dataclasses.field(default_factory=_empty_float32)
has_attack: npt.NDArray[np.bool_] = dataclasses.field(default_factory=_empty_bool)
low_frequency_energy: npt.NDArray[np.float32] = dataclasses.field(default_factory=_empty_float32)
subdivision_accent: npt.NDArray[np.float32] = dataclasses.field(default_factory=_empty_float32)
chord_change: npt.NDArray[np.float32] = dataclasses.field(default_factory=_empty_float32)
# Meter estimated over a caller-supplied beat series.
@dataclass(frozen=True, slots=True, eq=False)
class MeterEstimate:
time_signature: TimeSignature
downbeat_phase: int
searched: bool
grouping: npt.NDArray[np.int32] = dataclasses.field(default_factory=_empty_int32)
candidate_scores: npt.NDArray[np.float32] = dataclasses.field(default_factory=_empty_float32)
candidates: list[TimeSignature] = dataclasses.field(default_factory=list)
unobserved_beats: npt.NDArray[np.int32] = dataclasses.field(default_factory=_empty_int32)Chords
Chord.name is the chord symbol ("Am7", "C/E", "N.C." for no chord). The analysis functions fill it; a chord built by hand carries whatever name it is given. quality is a CHORD_QUALITIES token (see Chord qualities), "unknown" if not named. confidence is the correlation of the chroma with the chosen chord template, in [0, 1]. bass is the bass pitch class, None when no bass was estimated. duration_sec is end_sec - start_sec; root_name and bass_name are the core's canonical spelling, stable across all language bindings.
detect_chords returns a ChordAnalysisResult whose tuning_cents is the tuning the chroma was built with, as for KeyDetection. Inside analyze, chords are AnalysisChord records with roman_numeral relative to the analysis key, empty for N.C. chord_functions and chord_functional_analysis return FunctionalChord records: every Chord field unchanged, roman_numeral ("I", "V7", "vi"; "N.C." for an unknown chord) and function, one of "tonic", "subdominant", "dominant", "chromatic" for a root outside the key's scale, or "none" for an unknown chord.
# Detected chord with timing and confidence.
@dataclass(frozen=True, slots=True)
class Chord:
root: PitchClass
quality: str
start_sec: float
end_sec: float
confidence: float
bass: PitchClass | None = None
name: str = ''
# Chord length in seconds, ``end_sec - start_sec``.
@property
def duration_sec(self) -> float: ...
# Canonical core spelling, stable across all language bindings.
@property
def root_name(self) -> str: ...
# Canonical core spelling, stable across all language bindings.
@property
def bass_name(self) -> str: ...
# A chord of :func:`analyze`, labelled with a Roman numeral in the analysis key.
@dataclass(frozen=True, slots=True)
class AnalysisChord(Chord):
roman_numeral: str = ''
root: PitchClass
quality: str
start_sec: float
end_sec: float
confidence: float
bass: PitchClass | None = None
name: str = ''
# Chord length in seconds, ``end_sec - start_sec``.
@property
def duration_sec(self) -> float: ...
# Canonical core spelling, stable across all language bindings.
@property
def root_name(self) -> str: ...
# Canonical core spelling, stable across all language bindings.
@property
def bass_name(self) -> str: ...
# A timed chord labelled relative to a key by :func:`chord_functions`.
@dataclass(frozen=True, slots=True)
class FunctionalChord(Chord):
roman_numeral: str = ''
function: ChordFunctionName = 'none'
root: PitchClass
quality: str
start_sec: float
end_sec: float
confidence: float
bass: PitchClass | None = None
name: str = ''
# Chord length in seconds, ``end_sec - start_sec``.
@property
def duration_sec(self) -> float: ...
# Canonical core spelling, stable across all language bindings.
@property
def root_name(self) -> str: ...
# Canonical core spelling, stable across all language bindings.
@property
def bass_name(self) -> str: ...
# Chord detection primitives.
@dataclass(frozen=True, slots=True)
class ChordAnalysisResult:
chords: list[Chord]
tuning_cents: float = 0.0Rhythm, timbre and dynamics
analyze_rhythm, analyze_timbre and analyze_dynamics return the primitives below; analyze embeds the smaller summaries AnalysisRhythm, AnalysisDynamics and a TimbreFrame.
RhythmResult.bpmisNonewhen tempo cannot be measured. Measuredsyncopation,pattern_regularity, andtempo_stabilityfall in[0, 1]; unmeasured values areNone.groove_typeis a groove token, andbeat_intervalsreports the gaps between beats in seconds.- The timbre scores
brightness,warmth,density,roughnessandcomplexityare each in[0, 1], high meaning bright, warm, rich, rough or complex.TimbreResultadds per-framespectral_centroid,spectral_flatnessandspectral_rolloff, andtimbre_over_timeholds oneTimbreFrameper analysis window. In a window with no spectral energy, unmeasured timbre scores areNone. DynamicsResultreportsdynamic_range_db,peak_dbandrms_dbin dB,crest_factoras the peak-to-RMS ratio,loudness_range_luin LU, andis_compressed.loudness_times_secandloudness_rms_dbare the loudness curve's timestamps and levels, parallel to each other.
# Rhythm analysis primitives.
@dataclass(frozen=True, slots=True, eq=False)
class RhythmResult:
bpm: float | None
time_signature: TimeSignature
groove_type: str
syncopation: float | None
pattern_regularity: float | None
tempo_stability: float | None
beat_intervals: npt.NDArray[np.float32]
# Rhythm summary embedded in :class:`AnalysisResult`.
@dataclass(frozen=True, slots=True)
class AnalysisRhythm:
time_signature: TimeSignature
syncopation: float | None
groove_type: str
pattern_regularity: float | None
tempo_stability: float | None
# Timbre metrics for one analysis window in TimbreResult.timbre_over_time.
@dataclass(frozen=True, slots=True)
class TimbreFrame:
brightness: float | None
warmth: float | None
density: float | None
roughness: float | None
complexity: float | None
# Timbre and spectral-shape analysis primitives.
@dataclass(frozen=True, slots=True, eq=False)
class TimbreResult:
brightness: float | None
warmth: float | None
density: float | None
roughness: float | None
complexity: float | None
spectral_centroid: npt.NDArray[np.float32]
spectral_flatness: npt.NDArray[np.float32]
spectral_rolloff: npt.NDArray[np.float32]
timbre_over_time: list[TimbreFrame]
# Dynamics and loudness analysis primitives.
@dataclass(frozen=True, slots=True, eq=False)
class DynamicsResult:
dynamic_range_db: float | None
peak_db: float
rms_db: float
crest_factor: float | None
loudness_range_lu: float | None
is_compressed: bool
loudness_times_sec: npt.NDArray[np.float32]
loudness_rms_db: npt.NDArray[np.float32]
# Dynamics summary embedded in :class:`AnalysisResult`.
@dataclass(frozen=True, slots=True)
class AnalysisDynamics:
dynamic_range_db: float | None
peak_db: float
rms_db: float
crest_factor: float | None
loudness_range_lu: float | None
is_compressed: boolFull analysis result
analyze and Audio.analyze return an AnalysisResult, which composes the records above. bpm_confidence is the winning tempo cluster's vote share within 60 to 200 BPM, searched at 22050 Hz. downbeats are the beats that open a bar, so the list is not the length of beats; downbeat_phase is the beat index the first bar starts on. bpm_candidates has the chosen tempo first and time_signature_candidates is ordered by descending support. beat_observations is None when it was not produced. beat_local_bpm is the smoothed local tempo at each beat in BPM, parallel to beats, and may be empty. form is a form label such as "AABA", empty when none was derived, and tuning_cents is the tuning the chromagrams were built with. melody (MelodyResult) and sections (Section) are documented on Python Analysis API. Room acoustics are not part of the result.
# Full audio analysis result.
@dataclass(frozen=True, slots=True, eq=False)
class AnalysisResult:
bpm: float | None
bpm_confidence: float
key: Key
time_signature: TimeSignature
timbre: TimbreFrame
dynamics: AnalysisDynamics
rhythm: AnalysisRhythm
melody: MelodyResult
beats: list[Beat] = dataclasses.field(default_factory=list)
downbeats: list[Beat] = dataclasses.field(default_factory=list)
downbeat_phase: int = 0
bpm_candidates: list[AnalysisBpmCandidate] = dataclasses.field(default_factory=list)
time_signature_candidates: list[TimeSignature] = dataclasses.field(default_factory=list)
chords: list[AnalysisChord] = dataclasses.field(default_factory=list)
sections: list[Section] = dataclasses.field(default_factory=list)
beat_observations: BeatObservations | None = None
beat_local_bpm: npt.NDArray[np.float32] = dataclasses.field(default_factory=_empty_float32)
form: str = ''
tuning_cents: float = 0.0Spectral feature results
Matrix fields are float32 arrays shaped (rows, n_frames), as in the matrix layout note.
StftResult.magnitudeandpowerare(n_bins, n_frames);dbis the magnitude in dB with the same shape, orNoneunless the transform was asked for it.MelSpectrogramResultcarries the forward transform's parameters, so the result alone can be inverted:n_fft,fmin_hz,fmax_hzas applied (the Nyquist when the request omitted it; an explicit 0 is refused) andhtk(Truefor the HTK Mel formula,Falsefor Slaney).poweris linear power anddbits dB form, both(n_mels, n_frames).MfccResult.coefficientsis(n_mfcc, n_frames), with the Mel parameters it was derived from;lifteris the cepstral lifter applied, 0 meaning none.ChromaResult.featuresis(n_chroma, n_frames)andmean_energythe mean energy of each of then_chromaclasses.CqtResultis returned bycqt,hybrid_cqt,pseudo_cqtandvqt:magnitudeis(n_bins, n_frames)andfrequenciesthen_binscenter frequencies in Hz.gammais the bandwidth offset in Hz the transform ran with, the resolved value forvqtand 0 for the constant-Q transforms.PiptrackResult.pitchesandmagnitudesare(n_bins, n_frames).ReassignedSpectrogramResult.magnitude,times(seconds) andfrequencies(Hz) have the same shape.
# Short-time Fourier transform result.
@dataclass(frozen=True, slots=True, eq=False)
class StftResult:
n_fft: int
hop_length: int
sample_rate: int
magnitude: NDArray[np.float32]
power: NDArray[np.float32]
db: NDArray[np.float32] | None = None
phase: NDArray[np.float32] | None = None
# Mel spectrogram result.
@dataclass(frozen=True, slots=True, eq=False)
class MelSpectrogramResult:
sample_rate: int
hop_length: int
power: NDArray[np.float32]
db: NDArray[np.float32]
n_fft: int
fmin_hz: float
fmax_hz: float
htk: bool
# MFCC (Mel-frequency cepstral coefficients) result.
@dataclass(frozen=True, slots=True, eq=False)
class MfccResult:
coefficients: NDArray[np.float32]
sample_rate: int
hop_length: int
n_fft: int
n_mels: int
fmin_hz: float
fmax_hz: float
htk: bool
lifter: float
# Chroma feature result.
@dataclass(frozen=True, slots=True, eq=False)
class ChromaResult:
sample_rate: int
hop_length: int
features: NDArray[np.float32]
mean_energy: NDArray[np.float32]
# Constant-Q / Variable-Q transform magnitude result.
@dataclass(frozen=True, slots=True, eq=False)
class CqtResult:
hop_length: int
sample_rate: int
magnitude: NDArray[np.float32]
frequencies: NDArray[np.float32]
gamma: float
# Per-bin pitch candidates and peak magnitudes from spectral piptrack.
@dataclass(frozen=True, slots=True, eq=False)
class PiptrackResult:
pitches: NDArray[np.float32]
magnitudes: NDArray[np.float32]
# Magnitude and reassigned coordinates of an STFT.
@dataclass(frozen=True, slots=True, eq=False)
class ReassignedSpectrogramResult:
magnitude: NDArray[np.float32]
times: NDArray[np.float32]
frequencies: NDArray[np.float32]Pitch results
PitchResult is returned by pitch_yin and pitch_pyin. f0 is the per-frame fundamental frequency in Hz, NaN on unvoiced frames; voiced_flag is the voicing decision and the value to gate on. voiced_prob is pYIN's per-frame voiced observation mass, not a signal-quality confidence and not a correction weight: it depends on how many periods of the pitch fit in frame_length, so for a fixed frame length it rises with F0 even when the signal is unchanged. Thresholding it at a fixed 0.5 (the default in note_segments) therefore drops entire low registers.
note_segments returns NoteSegment records: frame_start and frame_end index the F0 frames (the end is exclusive), start_sec and end_sec are in seconds, and median_cents is the note's median pitch in cents.
# Pitch detection result.
@dataclass(frozen=True, slots=True, eq=False)
class PitchResult:
f0: NDArray[np.float32]
voiced_prob: NDArray[np.float32]
voiced_flag: NDArray[np.bool_]
median_f0: float | None
mean_f0: float | None
# One stable monophonic note region segmented from an F0 track.
@dataclass(frozen=True, slots=True)
class NoteSegment:
frame_start: int
frame_end: int
start_sec: float
end_sec: float
median_cents: floatLoudness and metering reports
LufsResultfollows ITU-R BS.1770 / EBU R128.momentary_lufsandshort_term_lufsare the loudness of the final complete 400 ms and 3 s windows, not Max-M and Max-S;max_momentary_lufsandmax_short_term_lufsare those maxima.LufsSeriesResultholds the whole series asfloat32arrays; a window the signal is too short for is empty.ClippingReportaggregatesdetect_clipping:clipped_samplescounts samples at or past the threshold,clipping_ratiodivides that by the input length, andregionslists the clipped runs in order. AClippingRegiongivesstart_sample,end_sample(one past the last clipped sample),lengthand the run's largest absolute sample valuepeak(linear).DynamicRangeReport.dynamic_range_dbis the high percentile minus the low percentile of the window levels; the percentile levels andwindow_rms_dbare in dBFS.SpectrumReportis one spectrum:frequenciesin Hz, linearmagnitude,poweranddb, with then_fftandsample_rateit was computed at.PhaseScopeReportcarries the point seriesmid,side,radiusandangle_rad(atan2(side, mid)), pluscorrelation,average_abs_angle_radandmax_radiusmeasured over the full-resolution signal.VectorscopeReportis themidandsideseries alone.WaveformPeaksReportarrays are channel-major: the value for a channel and bucket is at indexchannel * bucket_count + bucket.samples_per_bucketis the bucket width in samples.
# ITU-R BS.1770 / EBU R128 loudness metrics.
@dataclass(frozen=True, slots=True)
class LufsResult:
integrated_lufs: float
momentary_lufs: float | None
short_term_lufs: float | None
max_momentary_lufs: float | None
max_short_term_lufs: float | None
loudness_range_lu: float | None
# Momentary and short-term loudness series; a window the signal is too short for is empty.
@dataclass(frozen=True, slots=True, eq=False)
class LufsSeriesResult:
momentary_lufs: npt.NDArray[np.float32]
short_term_lufs: npt.NDArray[np.float32]
# One contiguous run of clipped samples reported by detect_clipping.
@dataclass(frozen=True, slots=True)
class ClippingRegion:
start_sample: int
end_sample: int
length: int
peak: float
# Aggregated clipping detection result (mirrors SonareClippingResult).
@dataclass(frozen=True, slots=True)
class ClippingReport:
clipped_samples: int
clipping_ratio: float
max_clipped_peak: float
regions: list[ClippingRegion]
# Sliding-window dynamic range report (mirrors SonareDynamicRangeResult).
@dataclass(frozen=True, slots=True, eq=False)
class DynamicRangeReport:
dynamic_range_db: float | None
low_percentile_db: float | None
high_percentile_db: float | None
window_rms_db: npt.NDArray[np.float32]
# Single-frame magnitude / power / dB spectrum (mirrors SonareSpectrumResult).
@dataclass(frozen=True, slots=True)
class SpectrumReport:
frequencies: NDArray[np.float32]
magnitude: NDArray[np.float32]
power: NDArray[np.float32]
db: NDArray[np.float32]
n_fft: int
sample_rate: int
# Phase-scope (Lissajous) point series plus summary stats.
@dataclass(frozen=True, slots=True)
class PhaseScopeReport:
mid: NDArray[np.float32]
side: NDArray[np.float32]
radius: NDArray[np.float32]
angle_rad: NDArray[np.float32]
correlation: float | None
average_abs_angle_rad: float | None
max_radius: float
# Mid/side vectorscope point series for a (left, right) stereo pair.
@dataclass(frozen=True, slots=True)
class VectorscopeReport:
mid: NDArray[np.float32]
side: NDArray[np.float32]
# Per-channel min/max waveform buckets.
@dataclass(frozen=True, slots=True)
class WaveformPeaksReport:
min: NDArray[np.float32]
max: NDArray[np.float32]
num_channels: int
bucket_count: int
samples_per_bucket: int