Skip to content

Python Audio API ​

Audio is the owned, mono sample buffer of the libsonare Python package: load or wrap samples once, then call the analysis, feature, loudness, effects and mastering functions as methods on it. DecodedChannels is what decode_channels returns when every source channel is wanted instead of a mono fold. The functions the methods wrap are on Python Analysis API, Python Feature Extraction API, Python Effects API, Python Metering and Signal Helpers API and Python Mastering API; the records they return are on Python Analysis Types and Python Effects Types.

Creating an Audio ​

Four constructors cover the sources. Audio(handle, lib) itself is internal: build an instance with a classmethod.

ConstructorSource
Audio.from_file(path, channel_index=None)A file on disk. WAV and MP3 in default builds; M4A/AAC/FLAC/OGG/Opus and any other container the linked FFmpeg supports when the library is built with -DSONARE_WITH_FFMPEG=ON
Audio.from_memory(data)Encoded audio bytes, with the same format support as from_file
Audio.from_buffer(samples, sample_rate)A mono float sample sequence in nominally [-1.0, 1.0]
Audio.file_num_channels(path)Not a constructor: probes the source channel count of a file without decoding it

An Audio carries a single channel, so a multi-channel source is downmixed into it. To keep the channels, either load one at a time with from_file(path, channel_index=n) (paired with file_num_channels; each load decodes the file once, so a stereo load costs two decodes) or decode all of them at once with decode_channels, which returns a channel-planar array in the source's own channel order (5.1 is L R C LFE Ls Rs).

from_buffer takes a list, tuple, array.array or one-dimensional NumPy array. Multi-channel input has to be folded first with downmix(channels, "mono")[0]. An empty buffer or one holding NaN or Inf raises SonareValueError. A missing file raises SonareError with FILE_NOT_FOUND, and bytes or a file that cannot be decoded raise SonareError with DECODE_FAILED; the message names the decoder's reason. A channel_index the file does not have, or a negative one, raises SonareValueError.

The Audio class ​

python
# Wrapper around the SonareAudio opaque pointer.
class Audio:
    def __init__(self, handle: ctypes.c_void_p, lib: ctypes.CDLL) -> None: ...
    # Load audio from a file path.
    @classmethod
    def from_file(cls, path: str, channel_index: int | None = None) -> Audio: ...
    # Return the source channel count encoded in an audio file.
    @classmethod
    def file_num_channels(cls, path: str) -> int: ...
    # Create audio from a float sample buffer.
    @classmethod
    def from_buffer(cls, samples: Sequence[float] | list[float], sample_rate: int) -> Audio: ...
    # Create audio from in-memory encoded audio bytes.
    @classmethod
    def from_memory(cls, data: bytes) -> Audio: ...
    # Return audio samples as a ``float32`` numpy array.
    @property
    def data(self) -> np.ndarray: ...
    # Return the number of audio samples.
    @property
    def length(self) -> int: ...
    # Return the sample rate in Hz.
    @property
    def sample_rate(self) -> int: ...
    # Return the audio duration in seconds.
    @property
    def duration_sec(self) -> float: ...
    # Detect BPM (tempo).
    def detect_bpm(
        self,
        *,
        bpm_min: float | None = None,
        bpm_max: float | None = None,
    ) -> float | None: ...
    # Detect musical key and the tuning its chroma was built with.
    def detect_key(
        self,
        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: ...
    # Return ranked musical key candidates; ``tuning_cents`` is as for :meth:`detect_key`.
    def detect_key_candidates(
        self,
        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 beat times in seconds.
    def detect_beats(
        self,
        *,
        bpm_min: float | None = None,
        bpm_max: float | None = None,
    ) -> np.ndarray: ...
    # Detect downbeat times in seconds.
    def detect_downbeats(self) -> np.ndarray: ...
    # Detect onset times in seconds as a float32 array.
    def detect_onsets(self) -> np.ndarray: ...
    # Run full music analysis, forwarding to the module-level :func:`libsonare.analyze`.
    def analyze(self, **kwargs: Any) -> AnalysisResult: ...
    # Analyze BPM with candidates and intermediate curves.
    def analyze_bpm(
        self,
        bpm_min: float | None = None,
        bpm_max: float | None = None,
        n_fft: int = 2048,
        hop_length: int = 512,
        max_candidates: int = 5,
    ) -> BpmAnalysisResult: ...
    # Analyze RT60, EDT, and clarity metrics treating this audio as an impulse response.
    def analyze_impulse_response(self, n_octave_bands: int = 6) -> AcousticResult: ...
    # Estimate blind RT60 from this audio (EDT and clarity read as NaN).
    def detect_acoustic(
        self,
        n_octave_bands: int = 6,
        n_third_octave_subbands: int = 24,
        min_decay_db: float = 30.0,
        noise_floor_margin_db: float = 10.0,
    ) -> AcousticResult: ...
    # Analyze rhythm primitives.
    def analyze_rhythm(
        self,
        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(
        self,
        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(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        n_mels: int = 128,
        n_mfcc: int = 13,
        window_sec: float = 0.5,
    ) -> TimbreResult: ...
    # Detect chord segments.
    def detect_chords(
        self,
        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: str = 'cqt',
        tuning_cents: float | str = 'auto',
    ) -> ChordAnalysisResult: ...
    # Perform harmonic-percussive source separation.
    def hpss(
        self,
        kernel_harmonic: int = 31,
        kernel_percussive: int = 31,
        with_residual: bool = False,
    ) -> HpssResult: ...
    # Extract the harmonic component.
    def harmonic(self) -> np.ndarray: ...
    # Extract the percussive component.
    def percussive(self) -> np.ndarray: ...
    # Time-stretch audio without changing pitch; ``speed_ratio`` > 1 shortens.
    def time_stretch(self, speed_ratio: float) -> np.ndarray: ...
    # Shift the pitch of audio by ``pitch_semitones`` (positive = up).
    def pitch_shift(self, pitch_semitones: float) -> np.ndarray: ...
    # Pitch-correct audio from a current MIDI note to a target MIDI note.
    def pitch_correct_to_midi(self, current_midi: float, target_midi: float) -> np.ndarray: ...
    # Time-stretch a single note region without changing pitch.
    def note_stretch(
        self,
        onset_sample: int | None = None,
        offset_sample: int | None = None,
        stretch_ratio: float = 1.0,
        *,
        onset_sec: float | None = None,
        offset_sec: float | None = None,
    ) -> np.ndarray: ...
    # Move a note region.
    def note_move(
        self,
        onset_sample: int | None = None,
        offset_sample: int | None = None,
        target_onset_sample: int | None = None,
        *,
        onset_sec: float | None = None,
        offset_sec: float | None = None,
        target_onset_sec: float | None = None,
    ) -> np.ndarray: ...
    # Apply a voice-change effect with independent pitch and formant control.
    def voice_change(
        self,
        pitch_semitones: float = 0.0,
        formant_factor: float = 1.0,
        formant_mode: str = 'relative',
    ) -> np.ndarray: ...
    # Apply the integrated realtime voice changer chain offline.
    def realtime_voice_changer_render(
        self,
        *,
        config: VoicePresetId | RealtimeVoiceChangerPreset | RealtimeVoiceChangerConfig | None = 'neutralMonitor',
    ) -> np.ndarray: ...
    # Normalize the peak or RMS level; see :func:`libsonare.normalize`.
    def normalize(
        self,
        *,
        mode: NormalizeMode = 'peak',
        target_db: float | None = None,
    ) -> np.ndarray: ...
    # Apply mastering loudness normalization with a true-peak ceiling.
    def mastering(
        self,
        target_lufs: float = -14.0,
        ceiling_dbtp: float = -1.0,
        true_peak_oversample: int | None = None,
        release_ms: float | None = None,
        apply_gain_at_input_rate: bool = False,
    ) -> MasteringResult: ...
    # Apply a named mastering processor.
    def mastering_apply_processor(
        self,
        processor: str,
        params: dict[str, float | int | bool | str] | None = None,
    ) -> MasteringResult: ...
    # Master this audio with a named preset, a chain of overrides, or both.
    def master_audio(
        self,
        *,
        preset: str | None = None,
        overrides: MasteringChainConfigInput | None = None,
        on_progress: Callable[[float, str], None] | None = None,
        cancel: Callable[[], bool] | None = None,
    ) -> MasteringChainResult: ...
    # Trim silence from the beginning and end.
    def trim(self, threshold_db: float = -60.0) -> np.ndarray: ...
    # Compute the short-time Fourier transform.
    def stft(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        *,
        db: bool = False,
        phase: bool = False,
    ) -> StftResult: ...
    # Compute a Mel spectrogram.
    def mel_spectrogram(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        n_mels: int = 128,
    ) -> MelSpectrogramResult: ...
    # Compute Mel-frequency cepstral coefficients.
    def mfcc(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        n_mels: int = 128,
        n_mfcc: int = 20,
    ) -> MfccResult: ...
    # Compute chroma features.
    def chroma(self, n_fft: int = 2048, hop_length: int = 512) -> ChromaResult: ...
    # Compute NNLS chroma as a float32 array of shape ``(12, n_frames)``.
    def nnls_chroma(self) -> np.ndarray: ...
    # Compute the onset strength envelope (float32, one value per frame).
    def onset_strength(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        n_mels: int = 128,
    ) -> np.ndarray: ...
    # Compute integrated/momentary/short-term LUFS and loudness range.
    def lufs(self) -> LufsResult: ...
    # Compute the per-block momentary LUFS time series as a float32 array.
    def momentary_lufs(self) -> np.ndarray: ...
    # Compute the per-block short-term LUFS time series as a float32 array.
    def short_term_lufs(self) -> np.ndarray: ...
    # Compute the spectral centroid per frame as a float32 array.
    def spectral_centroid(self, n_fft: int = 2048, hop_length: int = 512) -> np.ndarray: ...
    # Compute the spectral bandwidth per frame as a float32 array.
    def spectral_bandwidth(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        p: float = 2.0,
    ) -> np.ndarray: ...
    # Compute the spectral rolloff per frame as a float32 array.
    def spectral_rolloff(
        self,
        n_fft: int = 2048,
        hop_length: int = 512,
        roll_percent: float = 0.85,
    ) -> np.ndarray: ...
    # Compute the spectral flatness per frame as a float32 array.
    def spectral_flatness(self, n_fft: int = 2048, hop_length: int = 512) -> np.ndarray: ...
    # Compute the zero-crossing rate per frame as a float32 array.
    def zero_crossing_rate(self, frame_length: int = 2048, hop_length: int = 512) -> np.ndarray: ...
    # Compute the RMS energy per frame as a float32 array.
    def rms_energy(self, frame_length: int = 2048, hop_length: int = 512) -> np.ndarray: ...
    # Estimate fundamental frequency using the YIN algorithm.
    def pitch_yin(
        self,
        frame_length: int = 2048,
        hop_length: int = 512,
        f0_min_hz: float = 65.0,
        f0_max_hz: float = 2093.0,
        threshold: float = 0.1,
    ) -> PitchResult: ...
    # Estimate fundamental frequency using the pYIN algorithm.
    def pitch_pyin(
        self,
        frame_length: int = 2048,
        hop_length: int = 512,
        f0_min_hz: float = 65.0,
        f0_max_hz: float = 2093.0,
        threshold: float = 0.1,
        fill_na: bool = False,
    ) -> PitchResult: ...
    # Resample audio to a different sample rate; returns a float32 array.
    def resample(self, target_sample_rate: int) -> np.ndarray: ...
    # Sample-peak in dBFS over the buffer.
    def peak_db(self) -> float: ...
    # RMS level in dBFS over the buffer.
    def rms_db(self) -> float: ...
    # DC offset (mean) of the buffer in linear amplitude.
    def dc_offset(self) -> float: ...
    # Crest factor in dB (peak_db - rms_db).
    def crest_factor_db(self) -> float: ...
    # Fraction of analysis frames whose RMS is below ``threshold_db``.
    def silence_ratio(
        self,
        threshold_db: float = -45.0,
        frame_length: int = 1024,
        hop_length: int = 256,
    ) -> float: ...
    # Inter-sample (true) peak in dBFS.
    def true_peak_dbtp(self, oversample_factor: int | None = None) -> float: ...
    # Detect clipped runs; see :func:`libsonare.metering_detect_clipping`.
    def detect_clipping(
        self,
        threshold_db: float | None = None,
        min_region_samples: int | None = None,
    ) -> ClippingReport: ...
    # Sliding-window dynamic range (high_percentile - low_percentile, in dB).
    def dynamic_range(
        self,
        window_sec: float | None = None,
        hop_sec: float | None = None,
        low_percentile: float | None = None,
        high_percentile: float | None = None,
    ) -> DynamicRangeReport: ...
    # Welch-averaged magnitude / power / dB spectrum over the whole buffer.
    def spectrum(
        self,
        n_fft: int | None = None,
        apply_octave_smoothing: bool = False,
        octave_fraction: int | None = None,
        db_ref: float | None = None,
        db_amin: float | None = None,
    ) -> SpectrumReport: ...
    # True single-frame mono magnitude / power / dB spectrum (one Hann-windowed FFT).
    def spectrum_frame(
        self,
        frame_offset: int = 0,
        n_fft: int | None = None,
        apply_octave_smoothing: bool = False,
        octave_fraction: int | None = None,
        db_ref: float | None = None,
        db_amin: float | None = None,
    ) -> SpectrumReport: ...
    # EBU R128 / Tech 3342 Loudness Range (LRA) in LU.
    def ebur128_loudness_range_lu(self) -> float: ...
    # Free the underlying audio resource.
    def close(self) -> None: ...
    # Return this audio; leaving the ``with`` block closes it.
    def __enter__(self) -> Audio: ...
    # Close the audio when the ``with`` block exits.
    def __exit__(self, *args: object) -> None: ...

data returns a copy of the native samples as a float32 array, so an array taken before close() stays valid after it. length, sample_rate and duration_sec read the buffer's properties. Once an Audio is closed, reading data or any of them, or calling a method, raises SonareError with INVALID_STATE.

Audio is a context manager; leaving the with block closes it:

python
from libsonare import Audio

with Audio.from_file("music.mp3") as audio:
    result = audio.analyze()

What the methods do ​

Most analysis, feature, loudness, effects and mastering functions exist as methods. A method supplies samples and sample_rate from the object and takes the function's options after that, so audio.detect_bpm(bpm_min=80) stands for detect_bpm(audio.data, audio.sample_rate, bpm_min=80); the generated signatures above show which options each method keeps. They return the same records as the functions: AnalysisResult, StftResult, LufsResult, HpssResult, MasteringResult and so on.

Each detect_* call runs its own analysis and nothing is cached, so four calls run the pipeline four times; use analyze() for everything at once. Methods exist beyond the detect_* family for the focused analyses analyze_bpm, analyze_rhythm, analyze_dynamics, analyze_timbre, analyze_impulse_response, detect_acoustic and a positional detect_chords. Some focused functions have no method (analyze_sections, analyze_melody, cqt, vqt); pass audio.data and audio.sample_rate to those.

Decoded channels ​

python
# Result of :func:`decode_channels`.
@dataclass(frozen=True, slots=True, eq=False)
class DecodedChannels:
    sample_rate: int
    channels: np.ndarray

channels is a channel-planar float32 array of shape (num_channels, frames) in the source's own channel order, the shape the N-channel entry points take. sample_rate is the decoded audio's rate in Hz. decode_channels raises SonareError for empty bytes, undecodable input, a non-finite sample, or a sample rate outside the supported range.

Encoding and tags ​

encode_audio writes channel-planar samples to an in-memory buffer using one of the WAV, FLAC, MP3, OGG, Opus or M4A format tokens; formats whose optional encoder is absent from the build raise SonareError (NOT_SUPPORTED). Optional tags are a string-to-string mapping. Omit bit_depth for the format default and quality when the encoder default applies. Unequal channel lengths and a zero bit depth raise SonareValueError; non-mapping tags raise TypeError. read_audio_tags returns normalized text tags without decoding samples, raises TypeError unless data is bytes, and raises coded SonareError for unsupported or malformed audio bytes.

python
from libsonare import encode_audio, read_audio_tags

encoded = encode_audio([[0.0, 0.1, -0.1, 0.0]], 48000, "wav", tags={"title": "example"})
assert read_audio_tags(encoded)["title"] == "example"
python
# Encode channel-planar samples into an in-memory audio file.
def encode_audio(
    channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
    sample_rate: int,
    format: str,
    *,
    tags: Mapping[str, str] | None = None,
    bit_depth: int | None = None,
    quality: float | None = None,
) -> bytes: ...

# Read normalized container tags from audio bytes without decoding samples.
def read_audio_tags(data: bytes) -> dict[str, str]: ...