Python API
libsonare provides Python bindings for scripts, notebooks, batch jobs, and local desktop tools. The package calls the native libsonare library through ctypes, so Python code can use the compiled C/C++ engine without building a custom extension. PyPI wheels are available for supported Linux and macOS targets.
What is ctypes (and the C API)?
libsonare's core is compiled C/C++. ctypes is Python's built-in way to call functions in a compiled shared library (.so/.dylib) directly, with no extra C extension to build. The Python package forwards your calls to the same native code the C++ library runs, so you get native speed from plain Python. ("C API" means the flat set of C functions Python calls under the hood.)
Use this page when you want scripts, notebooks, batch analysis, or local tools that can read files directly. The Python package is usually the easiest route if you are not building a browser UI. The reference continues on sibling pages, listed in the reference map: analysis and feature extraction, mastering and mixing, effects and room acoustics, streaming processors, projects, instruments, the realtime engine, and the result and option types.
Python Mental Model
| Step | What happens |
|---|---|
| 1. Load audio | Audio.from_file(...) reads supported file formats into samples |
| 2. Inspect or process | Call detect_bpm, analyze, feature functions, editing DSP, mastering, or mixing APIs |
| 3. Use results | Print values, save JSON, render audio, or feed features into your own pipeline |
Most Python APIs accept raw sample arrays plus sample_rate. Raw samples are the decoded audio values, not an MP3 or WAV filename. The Audio object is a convenience for file-based workflows: load once, then call analysis or processing methods on the same object.
For a first script, keep it this small:
audio = sonare.Audio.from_file("song.mp3").- call
sonare.detect_bpm(audio.data, audio.sample_rate)orsonare.analyze(audio.data, audio.sample_rate); - print the result or save it as JSON.
Start with Audio or call functions directly
If your workflow begins with an audio file, start with Audio.from_file(...). If you already have samples from NumPy or another loader, call module-level functions such as detect_bpm(samples, sample_rate) directly.
How To Read This Reference
Read this page in three passes:
- If you are loading files, start with
Audio.from_file(...); if you already have samples, call the module-level functions directly. - Use Pick The Smallest API That Solves The Job to choose a function family instead of scanning the full reference.
- Return to Types only when you need exact attribute names, row-major matrix shapes, or JS parity aliases.
A single analyze(...) call returns the all-in-one analysis result — chords, sections, timbre, dynamics, rhythm, melody, form, and per-beat strength — matching the other bindings. Reach for the focused functions below when you only need one field or want per-call options.
Pass the sample rate explicitly
sample_rate is a required argument of the analysis, metering and room-acoustic helpers (detect_bpm, analyze, metering_peak_db, analyze_impulse_response, detect_acoustic, estimate_room, …); only the spectral and feature functions that take sr= (stft, mfcc, cqt, …) default to 22050. When you load with Audio.from_file(...), pass audio.sample_rate, and pass it as sr= to a feature function too, so the 22050 default never silently applies to audio recorded at a different rate. An impulse response (IR) here is a recording of how a space responds to one short burst of sound.
Pick The Smallest API That Solves The Job
| You need | Start with | Why |
|---|---|---|
| A script that reads files and prints metadata | Audio.from_file(...) + detect_bpm / detect_key / analyze | Python handles decoding and keeps the code short |
| Detailed music analysis | analyze_bpm, detect_chords, analyze_sections, analyze_timbre, analyze_dynamics, analyze_rhythm | These run a single facet of analysis with extra parameters; analyze(...) already returns all of these fields in one AnalysisResult |
| Feature arrays for notebooks or ML | mel_spectrogram, mfcc, chroma, cqt, vqt, chroma_cqt, nnls_chroma | Returns plain Python lists / result objects that can be converted to NumPy if desired |
| Editing a clip | time_stretch, pitch_shift, pitch_correct_to_midi, note_stretch, voice_change, RealtimeVoiceChanger | These transform the signal itself |
| Mastering a file | master_audio, master_audio_stereo, StreamingMasteringChain | Presets first, explicit chain config when you need control |
| Live or chunked analysis | StreamAnalyzer | Feed audio blocks, drain feature frames, and read BPM/key/chord estimates that update as more audio arrives |
| Stem mixing | mix_stereo or Mixer(scene=...) | One-shot arrays first; scene mixer for sends, buses, automation, and meters |
| Room decay, clarity, equivalent-room estimates, or generated room character | analyze_impulse_response, detect_acoustic, estimate_room, synthesize_rir, room_morph (Python Room Acoustics API) | These describe or apply the room, not the song |
Installation
Requires Python 3.11 or later (3.11, 3.12, 3.13).
pip install libsonareThis also installs the sonare CLI command. See CLI Reference for details.
Default PyPI wheels decode WAV and MP3. Check libsonare.capabilities().features.ffmpeg for the loaded build. If you need direct M4A/AAC/FLAC/OGG/Opus decoding, clone the repository, build an FFmpeg-enabled wheel, and install that wheel:
git clone https://github.com/libraz/libsonare.git
cd libsonare
SONARE_FFMPEG=1 bash bindings/python/build_wheel.sh
python3 -m pip install bindings/python/dist/*.whlFFmpeg-enabled builds require FFmpeg development libraries. On macOS, install them with brew install ffmpeg. On Debian/Ubuntu, install libavformat-dev libavcodec-dev libavutil-dev libswresample-dev.
Building from Source (alternative)
If pre-built wheels are not available for your platform, you can build from source:
git clone https://github.com/libraz/libsonare.git
cd libsonare
cmake -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED=ON
cmake --build build -j
cd bindings/python
pip install -e .Requirements for building from source:
- Python 3.11+
- CMake 3.16+
- C++17 compiler (GCC or Clang on the supported Linux/macOS targets)
- Optional FFmpeg development libraries when building with
SONARE_FFMPEG=1
Quick Start
from libsonare import Audio, analyze, detect_bpm, detect_key, detect_beats
# Load audio from file
audio = Audio.from_file("music.mp3")
# Individual analysis
bpm = detect_bpm(audio.data, audio.sample_rate)
key = detect_key(audio.data, audio.sample_rate)
beats = detect_beats(audio.data, audio.sample_rate)
# All-in-one analysis
result = analyze(audio.data, audio.sample_rate)
print(f"BPM: {result.bpm} ({result.bpm_confidence:.0%})")
print(f"Key: {result.key}")
print(f"Time Signature: {result.time_signature}")
print(f"Beats: {len(result.beats)} detected")Error handling
Two exception classes cover every library failure, plus a plain TypeError for an argument of the wrong type. Which one a call raises depends on the cause, not on the entry point:
| Failure cause | Class | .code | CLI exit |
|---|---|---|---|
An argument of the wrong type: a string or bool for a number, a missing required argument | TypeError | none | 2 |
An argument whose value is refused: an empty or non-finite buffer, a fractional sample rate or one outside 8000 to 384000, an unknown preset or processor name, an unknown key in a typed scene, lengths that must match, an unknown id on Project or RealtimeEngine | SonareValueError | INVALID_PARAMETER (4) | 2 when the command-line parser knows the domain, 3 when the library refuses it after the input is read |
| A file that does not exist | SonareError | FILE_NOT_FOUND (1) | 4 |
A document that does not load: Project.from_json, Mixer.from_json, import_smf, mastering_chain_config_from_json | SonareError, not SonareValueError | INVALID_FORMAT (2) | 5 |
| Audio that will not decode: unreadable bytes or an unsupported container | SonareError | DECODE_FAILED (3) | 6 |
| An allocation failure | SonareError | OUT_OF_MEMORY (5) | 7 |
| A feature the loaded library does not carry, or an entry point it lacks | SonareError | NOT_SUPPORTED (6) | 8 |
| A closed or released object, or a refusal caused by earlier configuration | SonareError | INVALID_STATE (7) | 9 |
A run stopped by its cancel callback | SonareError | CANCELLED (8) | 11 |
| An output that cannot be written | SonareError | ENCODE_FAILED (9) | 12 |
| A native library from a different build than the binding | SonareError | ABI_MISMATCH (10) | 13 |
| A result its source has since invalidated | SonareError | STALE_RESULT (11) | 14 |
| A native result that fails a sanity check, or anything else | SonareError | UNKNOWN (99) | 10 |
A SonareError message carries a [code] prefix ([2] Invalid format); a SonareValueError message is plain validation text. SonareError subclasses RuntimeError, so except RuntimeError catches every row but the first. Native INVALID_PARAMETER also raises SonareValueError. SonareValueError subclasses both SonareError and ValueError: except ValueError: and except sonare.SonareError: each catch an argument refusal, while a document that fails to load is a plain SonareError that except ValueError: does not catch. A non-number for a numeric argument is a TypeError, which neither handler catches. SonareError.code holds the same C-ABI values the JS bindings expose as ErrorCode, and .code_name gives the cross-binding spelling. The error contract lines the same failures up with the other bindings and the C ABI. A library whose ABI version differs from the one the package was built for, or which lacks a symbol the binding needs, fails on first use with a message beginning libsonare ABI mismatch; Installation covers the fix.
try:
result = sonare.master_audio_stereo(left, right, sample_rate=48000, preset="pop")
except sonare.SonareError as e:
print(e.code, e.code_name, e)Arguments are checked before the call
Buffer-taking entry points preflight their arguments, so an empty, mis-sized, or non-finite buffer is reported against the function you called rather than against an internal helper or a bare C symbol:
master_audio_stereo: right must not be empty
spectral_centroid: samples contains a non-finite sample at index 0The names in the message are the ones in your call: segment_cross_similarity reports x and x_rows, not the internal data / rows spelling, and the scalar and stereo meters name the facade function (metering_peak_db) rather than the sonare_-prefixed C symbol.
If you match on message text
Handlers that catch SonareError or ValueError, or that branch on .code, need no change. Code that matches the text of a validation message does: the wording names the entry point and the argument.
Input some entry points refuse
trim_silence,split_silenceandfix_framesraise on an empty buffer instead of returning an empty result.tempogram_ratiorejects afactorsentry that is not finite and positive. A NaN reaches an undefined float-to-int cast in the core, and an infinity degenerates silently to the DC lag.mix_stereorefuses a scene it cannot mix — strips that are all empty, or a strip carrying NaN or Inf, named by strip index and channel (mix_stereo: strips[1][1] contains a non-finite sample at index 0). A zero-frame block stays a valid no-op at the C ABI, where it means "process this block" rather than "mix these strips".
What is not checked
The element-wise conversions keep their empty-in / empty-out contract: power_to_db, amplitude_to_db, db_to_power, db_to_amplitude, preemphasis, deemphasis, vector_normalize, frame_signal, pad_center and fix_length accept an empty sequence and return one. Among the tempo helpers only tempogram_ratio guards its input matrix; tempogram, fourier_tempogram, cyclic_tempogram and plp do not.
f0_hz is never scanned for non-finite values. pYIN marks an unvoiced frame with nan, and that track representation has to pass straight into pitch correction, so note_segments, extract_notes, decompose_note_pitch, split_note and merge_notes check its shape but not its values.
"Not given" is None
An optional numeric argument that has no value is left out or passed as None; -1 is not a spelling of "not given" and is refused with SonareValueError. This covers the engine's render_frame on every transport, parameter and MIDI call (None applies at the next block head), SpectralRegionOp.end_sample (None runs to the end of the signal), fix_frames(x_max=...), Project.set_program(bank_msb=..., bank_lsb=...) (omitting both emits no Bank Select), the percentiles of metering_dynamic_range and Audio.dynamic_range, and the gamma of vqt and vqt_to_audio (None selects the automatic bandwidth). The C ABI keeps -1 as its own spelling.
Argument-parser usage errors in the sonare CLI (an unknown flag, a missing argument, an integer option beyond int32 or a float option beyond float32) exit with code 2. A command that rejects a value raises a plain ValueError, not SonareValueError, because it reports a command-line mistake rather than an API argument; it exits with 3, the same code as a SonareValueError. An ABI mismatch exits with 13; see CLI exit codes.
What this build can do
capabilities() returns the build-diagnostics report sonare doctor prints, and capability_catalog() returns the machine-readable processor/parameter/preset catalog validated against schemas/capability-catalog.schema.json.
import libsonare as sonare
caps = sonare.capabilities()
if not caps.features.ffmpeg:
print("This wheel decodes:", caps.decode.builtin)
catalog = sonare.capability_catalog()
for processor in catalog.processors:
for param in processor.params:
# min / max / default are None when the core does not declare a bound.
build_slider(processor.id, param)Branch on the catalog rather than on a hand-maintained table: a parameter's range, default, unit, and realtime-safety all come from the loaded build. The same data is capabilities() / capabilityCatalog() on Node and WASM.
catalog.mastering_presets lists built-in mastering and restoration presets. Each entry has name, kind, target_lufs, true_peak_ceiling_dbtp, and max_limiter_gain_reduction_db; restoration entries set the three numeric fields to None. Processor entries also expose conditional parameter groups in slots, with name, parent, activation, and min_crossover_cutoffs fields.
Canceling a long call
Analysis and mastering calls that report progress also take cancel, a predicate polled at the same native boundaries. Return True and the call aborts with SonareError code 8 (SONARE_ERROR_CANCELLED), leaving no partial output.
import threading
stop = threading.Event()
try:
result = sonare.master_audio(
samples,
sample_rate,
preset="pop",
on_progress=lambda p, stage: print(stage, p),
cancel=stop.is_set,
)
except sonare.SonareError as e:
if e.code == 8:
print("cancelled")
else:
raiseReleasing Native Handles
Every object that owns native memory (Audio, Project, Mixer, RealtimeEngine, StreamAnalyzer, RealtimeVoiceChanger, StreamingMasteringChain, StreamingEqualizer, and so on) has close() and works as a context manager. Calling a method after close() raises SonareError with INVALID_STATE.
More entry points
Functions and types for areas covered by other pages; the full signatures are in the type stubs shipped with the package.
| Task | API | Guide |
|---|---|---|
| Label detected chords with Roman numerals and functions without re-detecting | chord_functions(chords, key) returning FunctionalChord entries | Analysis |
| Let the analysis measure the tuning, and convert it to Hz | tuning_cents on analyze, detect_chords, detect_key, detect_key_candidates (measured by default, tuning_cents=0 for A440; KeyDetection carries the tuning_cents used); reference_hz="auto" on transcribe; tuning_to_reference_hz, reference_hz_to_tuning | Audio To Notes |
| Tune a monophonic take to a detected or named key | auto_tune(samples, sample_rate, key="detect") returning AutoTuneResult (Python Effects API); scale_mask_for_mode(root, mode) (Python Analysis API) | Python Effects API |
| Invert a Mel or MFCC result | mel_to_stft, mel_to_audio, mfcc_to_mel, mfcc_to_audio; a MelSpectrogramResult or MfccResult carries the forward parameters (n_fft, fmin_hz, fmax_hz, htk, lifter) as attributes | Inverse Features |
| Convert a detected chord or key into an arrangement annotation | chord_symbol_from_analysis(chord), key_mode_from_analysis(mode) | Project Editing: MIDI |
Turn a room estimate into synthesize_rir input | room_geometry_from_estimate(estimate, source=..., listener=...) returning RoomGeometry (with source, listener and absorption derived from the estimate unless overridden) | Acoustic Analysis |
| Keep every decoded channel, or fold channels to a narrower layout | decode_channels(data) returning a DecodedChannels (channels, sample_rate), downmix(channels, target_layout) (centre and surround at -3 dB, LFE dropped) | Channel Formats |
| Render a buffer through an existing playback renderer | PlaybackRenderer.render_offline(samples, num_input_channels) resets the renderer, renders the interleaved buffer and returns an interleaved float32 array; diagnostics() afterwards describes that render. A closed renderer raises SonareError with INVALID_STATE | Playback Renderer |
Audio, project and live-device examples
Phase, tags and stereo analysis
Capture phase with stft to reconstruct the original sample length with istft. Pass one equally sized sample array per channel to the encoder. The tag reader takes the encoded bytes. Stereo pair analysis takes a left and a right plane for both inputs.
import numpy as np
import libsonare as sonare
sample_rate = 16000
t = np.arange(sample_rate, dtype=np.float32) / sample_rate
mono = (0.2 * np.sin(2 * np.pi * 440 * t)).astype(np.float32)
stereo = np.stack([mono, mono])
spectrum = sonare.stft(mono, sr=sample_rate, n_fft=256, hop_length=64, phase=True)
assert spectrum.phase is not None
reconstructed = sonare.istft(
spectrum.magnitude, spectrum.phase, n_fft=256, hop_length=64,
length_samples=mono.size,
)
wav = sonare.encode_audio(stereo, sample_rate, "wav", tags={"title": "440 Hz"})
print(sonare.read_audio_tags(wav)["title"])
print(sonare.mastering_analyze_pair(
"match.referenceLoudness", stereo, stereo * 0.5, sample_rate,
))Project readers
Tempo and time-signature readers return stored segments. The position reader reports the effective tempo, bar and beat at a PPQ position. Annotation readers preserve the stored order, including overlapping sections. Each automation lane has a project-assigned ID.
from libsonare import AutomationPoint, Project
with Project() as project:
project.set_tempo_segments([{"start_ppq": 0, "bpm": 120}])
project.set_time_signatures([{"start_ppq": 0, "numerator": 3, "denominator": 4}])
print(project.tempo_segments(), project.time_signatures())
ppq = project.bar_start_ppq(1)
print(project.position_at_ppq(ppq), project.sec_to_ppq(project.ppq_to_sec(ppq)))
project.annotate_keys([{"start_ppq": 0, "end_ppq": 6, "tonic_pc": 0, "mode": "major"}])
project.annotate_chords([{
"start_ppq": 0, "end_ppq": 3, "root_pc": 0, "quality": "major",
"extensions": [], "slash_bass_pc": None, "modulation_boundary": False,
}])
project.annotate_sections([
{"start_ppq": 0, "end_ppq": 4, "label": "Verse"},
{"start_ppq": 3, "end_ppq": 6, "label": "Chorus"},
])
print(project.key_annotations(), project.chord_annotations(), project.section_annotations())
print(project.mixer_scene(), project.unresolved_sound_font_uris())
track_id = project.add_track("audio", "Voice")
lane_id = project.add_automation_lane(
track_id, target_kind="trackFaderDb", points=[AutomationPoint(ppq=0, value=-3)],
)
print(lane_id, project.automation_lanes())MIDI CC bindings
Set consume to route matching controller messages to the parameter and suppress their delivery to the instrument. It defaults to false. The reader returns a snapshot whose order is unspecified.
from libsonare import MidiCcBinding, RealtimeEngine
with RealtimeEngine(48000) as engine:
engine.bind_midi_cc(MidiCcBinding(cc_number=1, param_id=42, consume=True))
print(engine.midi_cc_bindings())Live devices
Check capabilities().features.live_devices before enumerating devices or opening a session. This example opens the default output when the loaded library supports live devices. Read status() for device counters and captured_midi() to drain the events captured since the previous call.
from libsonare import LiveSession, RealtimeEngine, capabilities
if capabilities().features.live_devices:
print(LiveSession.audio_devices(), LiveSession.midi_sources())
with RealtimeEngine(48000) as engine:
with LiveSession(engine, audio_output="default") as session:
print(session.status(), session.captured_midi())Reference map
| Page | Covers |
|---|---|
| Python Audio API | The Audio class and DecodedChannels |
| Python Analysis API | The analysis functions, transcribe, version and capability queries |
| Python Feature Extraction API | Feature extraction and the NMF factors |
| Python Signal and Conversion API | Test signals and structure, inverse reconstruction, scale quantization, conversions, channel utilities |
| Python Metering and Signal Helpers API | Metering, framing, padding, peak picking, normalization and tempogram helpers |
| Python Effects API | Audio effects and effects functions |
| Python Room Acoustics API | Impulse-response analysis, room estimation, RIR synthesis and room morphing |
| Python Note Editing API | Note and percussive event editing, polyphonic analysis |
| Python Mastering API | Mastering chains, processors, presets, reference-track processing, the mastering assistant, audio profiles and delivery previews |
| Python Dynamics and Repair API | Standalone dynamics, repair, detection and trimming |
| Python Streaming API | The realtime voice changer, StreamingRetune, the streaming equalizer, StreamAnalyzer |
| Python Projects API | Project, vocal-edit sessions, assist sidecars, with their lifecycle |
| Python Project Edit API | Generated Project signatures for tracks, clips, warping, takes and editing |
| Python Project MIDI API | Generated Project signatures for MIDI clips, events, import and export |
| Python Mixer API | mix_stereo, the Mixer lifecycle and members, MixerStereoResult, StripRef, scene presets |
| Python Playback API | The playback renderer for movie audio |
| Python Realtime Engine API | RealtimeEngine lifecycle, transport, clips, parameters, capture and render |
| Python Engine Mixing API | Track lanes, buses, strips and clip page providers |
| Python Instruments and Live MIDI API | The built-in synthesizer, SoundFont and host instruments, SynthPatch, the engine's MIDI members |
| Python Instrument Types | Instrument records and tokens |
| Python Types | Result and option types, exceptions |
| Python Analysis Types | Key, tempo, beat, chord, rhythm, timbre, pitch and loudness results |
| Python Streaming Types | Frame batches, progressive estimates and stereo blocks |
| Python Effects Types | Separation, normalization, trimming, pitch correction, note editing and voice changer records |
| Python Mastering Types | Mastering, loudness matching, mono compatibility, assistant and mix-assistant results |
| Python Vocal Edit Types | Vocal analysis, notes, edit commands and edit results |
| Python Repair and Room Types | Detections, repair reports and stages, room acoustics and impulse responses |
| Python Engine Types | Transport, clips, capture, graph, bounce, telemetry and structure records |
| Python Capabilities Types | Build capabilities and the processor and preset catalog |
| Python Tokens and Aliases | String tokens, Literal aliases and constants the signatures name |