Skip to content

Python Signal and Conversion API ​

Test signals, structure analysis, inverse reconstruction, scale quantization, unit conversions, and channel and signal utilities of the libsonare Python package. Feature extraction is on Python Feature Extraction API, metering and framing helpers on Python Metering and Signal Helpers API, and installation, quick start, and the other API families on the Python API index.

Test signals, reconstruction, and structure ​

python
import libsonare as sonare

# Deterministic test signals — no asset files needed.
sine = sonare.tone(frequency=440.0, sr=48000, duration=1.0)
sweep = sonare.chirp(fmin=100.0, fmax=8000.0, sr=48000, duration=2.0)
track = sonare.clicks(times=[0.0, 0.5, 1.0], sr=48000)

# Reconstruction and per-bin pitch candidates.
audio_again = sonare.griffin_lim(magnitude, sample_rate=48000)   # magnitude: 2-D (n_bins, n_frames)
reassigned = sonare.reassigned_spectrogram(samples, sr=48000)
peaks = sonare.piptrack(samples, sr=48000)
delta = sonare.mel_delta(features)   # features: 2-D (n_features, n_frames)
flux = sonare.spectral_flux(samples, sample_rate=48000)
backtracked = sonare.onset_backtrack(onset_frames, energy)

# Note segmentation from a monophonic F0 track.
pitch = sonare.pitch_pyin(samples, sample_rate=48000)
segments = sonare.note_segments(
    pitch.f0,
    frame_rate=48000 / 512,
    voiced=pitch.voiced_flag,
    min_note_ms=60.0,
)
python
# Generate a sine tone as a float32 array.
def tone(
    frequency: float = 440.0,
    sr: int = 22050,
    duration: float = 1.0,
    phi: float = 0.0,
    amplitude: float = 1.0,
) -> np.ndarray: ...

# Generate a linear or exponential chirp as a float32 array.
def chirp(
    fmin: float = 440.0,
    fmax: float = 880.0,
    sr: int = 22050,
    duration: float = 1.0,
    linear: bool = False,
) -> np.ndarray: ...

# Generate decaying sine clicks at times in seconds as a float32 array.
def clicks(
    times: Sequence[float] | list[float],
    sr: int = 22050,
    length: int | None = None,
    click_freq: float = 1000.0,
    click_duration: float = 0.1,
) -> np.ndarray: ...

# Return magnitude, reassigned times and reassigned frequencies per STFT bin.
def reassigned_spectrogram(
    samples: Sequence[float] | list[float],
    sr: int = 22050,
    n_fft: int = 2048,
    hop_length: int = 512,
    ref_power: float = 1e-06,
    fill_nan: bool = False,
) -> ReassignedSpectrogramResult: ...

# Return per-bin spectral pitch candidates and their peak magnitudes.
def piptrack(
    samples: Sequence[float] | list[float],
    sr: int = 22050,
    n_fft: int = 2048,
    hop_length: int = 512,
    fmin: float = 150.0,
    fmax: float = 4000.0,
    threshold: float = 0.1,
) -> PiptrackResult: ...

# Compute first-order regression deltas of a feature matrix.
def mel_delta(features: npt.ArrayLike, width: int = 9) -> np.ndarray: ...

# Compute the unsigned L1 spectral-flux envelope as a float32 array.
def spectral_flux(
    samples: Sequence[float] | list[float],
    sample_rate: int,
    n_fft: int = 2048,
    hop_length: int = 512,
    lag: int = 1,
) -> np.ndarray: ...

# Backtrack onset event indices to local energy minima.
def onset_backtrack(
    events: Sequence[int] | list[int],
    energy: Sequence[float] | list[float],
) -> np.ndarray: ...

# Segment a monophonic F0 track into stable note regions.
def note_segments(
    f0_hz: Sequence[float] | list[float],
    frame_rate: float,
    *,
    voiced: Sequence[int] | list[int] | None = None,
    voiced_prob: Sequence[float] | list[float] | None = None,
    segmentation_threshold_cents: float | None = None,
    min_note_ms: float | None = None,
    reference_hz: float | None = None,
    voiced_threshold: float | None = None,
) -> list[NoteSegment]: ...

Pass voiced_flag, not voiced_prob

note_segments takes per-frame voicing as voiced (flags, non-zero = voiced), so feed it pitch_pyin's voiced_flag; the alternative voiced_prob is thresholded at voiced_threshold (default 0.5), and one of the two is required. voiced_prob is the frame's voiced observation mass: it depends on how many periods fit in the analysis window, so it rises with F0 rather than tracking confidence. At frame_length=2048 and 48 kHz a steady three-harmonic tone averages well under 0.1 at C2 and around 0.5 at C5 — so a bass or low-male-vocal track run against a fixed threshold returns an empty list and raises nothing. voiced_threshold is the other lever if you do want to segment on a continuous voicing value.

The structural-similarity family carries the same segment_ prefix as the JavaScript segment* names:

python
# Return column-wise cross-similarity (``librosa.segment.cross_similarity``).
def segment_cross_similarity(
    x: npt.ArrayLike,
    y: npt.ArrayLike,
    k: int | None = None,
    metric: Literal['cosine', 'euclidean'] = 'cosine',
    mode: Literal['connectivity', 'affinity'] = 'connectivity',
) -> np.ndarray: ...

# Return a self-similarity recurrence matrix (``librosa.segment.recurrence_matrix``).
def segment_recurrence_matrix(
    data: npt.ArrayLike,
    k: int | None = None,
    width: int = 1,
    sym: bool = False,
    metric: Literal['cosine', 'euclidean'] = 'euclidean',
    mode: Literal['connectivity', 'affinity'] = 'connectivity',
) -> np.ndarray: ...

# Convert a square recurrence matrix to a lag-by-time matrix.
def segment_recurrence_to_lag(recurrence: npt.ArrayLike, pad: bool = True) -> np.ndarray: ...

# Convert a lag matrix back to an ``(n, n)`` recurrence matrix.
def segment_lag_to_recurrence(lag: npt.ArrayLike) -> np.ndarray: ...

# Enhance diagonal paths in a square recurrence matrix of shape ``(n, n)``.
def segment_path_enhance(
    recurrence: npt.ArrayLike,
    win: int,
    max_ratio: int = 2,
    min_ratio: int | None = None,
    n_filters: int = 7,
) -> np.ndarray: ...

# Refine frame boundaries by clustering each parent segment.
def segment_subsegment(
    data: npt.ArrayLike,
    boundaries: Sequence[int] | list[int],
    n_segments: int = 4,
) -> np.ndarray: ...

# Cluster feature columns and return one label per column as an int32 array.
def segment_agglomerative(
    data: npt.ArrayLike,
    k: int,
    linkage: Literal['average', 'single', 'complete', 'ward'] = 'average',
) -> np.ndarray: ...
PythonJavaScript
segment_cross_similaritysegmentCrossSimilarity(...)
segment_recurrence_matrixsegmentRecurrenceMatrix(...)
segment_recurrence_to_lagsegmentRecurrenceToLag(...)
segment_lag_to_recurrencesegmentLagToRecurrence(...)
segment_path_enhancesegmentPathEnhance(...)
segment_subsegmentsegmentSubsegment(...)
segment_agglomerativesegmentAgglomerative(...)

segment_recurrence_to_lag takes an (n, n) recurrence matrix and returns librosa's lag-by-time layout, lag[l, i] = rec[(i + l) % n_lags, i]: 2n × n padded (the default) and n × n with pad=False. segment_lag_to_recurrence takes either height, n_lags being n or 2 * n, and returns the (n, n) matrix. JavaScript spells the padding pad: true on segmentRecurrenceToLag.

Pitch and feature terms: YIN/pYIN, zero-crossing rate, MIDI note
  • YIN / pYIN — algorithms that estimate the fundamental frequency (the perceived pitch) of monophonic audio. YIN uses autocorrelation; pYIN adds probabilistic smoothing so the pitch line stays steadier over time. Both track one note at a time, not chords.
  • Zero-crossing rate (ZCR) — how often the waveform crosses zero per frame. High ZCR means noisy or high-frequency content (cymbals, fricatives); low ZCR means smooth, tonal sound.
  • MIDI note number — an integer naming a pitch: A4 = 69, middle C = 60, each semitone ±1. hz_to_midi / midi_to_hz (below) convert between Hz and this scale.

Inverse Reconstruction Functions ​

Reconstruct a spectrum or audio from a mel spectrogram or MFCC matrix. Phase is estimated with Griffin-Lim, so the round-trip is lossy — see Inverse Features. Matrix inputs are 2-D arrays shaped (bands or bins, n_frames).

python
# Reconstruct audio from an STFT magnitude of shape ``(n_bins, n_frames)``.
def griffin_lim(
    magnitude: npt.ArrayLike,
    sample_rate: int,
    n_fft: int | None = None,
    hop_length: int | None = None,
    n_iter: int = 32,
    momentum: float = 0.99,
) -> np.ndarray: ...

# Approximate inverse of a Mel filterbank (Mel power -> STFT magnitude).
def mel_to_stft(
    mel: npt.ArrayLike,
    sr: int = 22050,
    n_fft: int = 2048,
    fmin: float = 0.0,
    fmax: float | None = None,
    htk: bool = False,
) -> np.ndarray: ...

# Reconstruct audio from a Mel spectrogram via Griffin-Lim.
def mel_to_audio(
    mel: npt.ArrayLike,
    sr: int = 22050,
    n_fft: int = 2048,
    hop_length: int | None = None,
    fmin: float = 0.0,
    fmax: float | None = None,
    n_iter: int = 32,
    htk: bool = False,
) -> np.ndarray: ...

# Invert MFCC coefficients back to a Mel power spectrogram.
def mfcc_to_mel(
    coefficients: npt.ArrayLike,
    n_mels: int = 128,
    lifter: float = 0.0,
) -> np.ndarray: ...

# Reconstruct audio directly from MFCC via Mel inversion + Griffin-Lim.
def mfcc_to_audio(
    coefficients: npt.ArrayLike,
    n_mels: int = 128,
    sr: int = 22050,
    n_fft: int = 2048,
    hop_length: int | None = None,
    fmin: float = 0.0,
    fmax: float | None = None,
    n_iter: int = 32,
    htk: bool = False,
    lifter: float = 0.0,
) -> np.ndarray: ...

# Reconstruct mono audio from a CQT magnitude via Griffin-Lim.
def cqt_to_audio(
    magnitude: npt.ArrayLike,
    sample_rate: int,
    hop_length: int = 512,
    fmin_hz: float = 32.70319566257483,
    bins_per_octave: int = 12,
    n_iter: int = 32,
) -> np.ndarray: ...

# Reconstruct mono audio from a VQT magnitude via Griffin-Lim.
def vqt_to_audio(
    magnitude: npt.ArrayLike,
    sample_rate: int,
    hop_length: int = 512,
    fmin_hz: float = 32.70319566257483,
    bins_per_octave: int = 12,
    gamma: float | None = None,
    n_iter: int = 32,
) -> np.ndarray: ...
FunctionDescription
griffin_limAudio from a STFT magnitude matrix (n_bins, n_frames); n_iter defaults to 32, momentum to 0.99
mel_to_stftLinear STFT magnitude (n_bins, n_frames) from a mel spectrogram (n_mels, n_frames)
mel_to_audioAudio from a mel spectrogram (Griffin-Lim)
mfcc_to_melMel power spectrogram from MFCC coefficients (n_mfcc, n_frames) (lifter must match the forward mfcc(...) call)
mfcc_to_audioAudio from MFCC coefficients
cqt_to_audioAudio from a CQT magnitude matrix (n_bins, n_frames) (Griffin-Lim)
vqt_to_audioAudio from a VQT magnitude matrix (n_bins, n_frames) (Griffin-Lim)

fmin defaults to 0.0 and fmax to the Nyquist frequency; n_iter defaults to 32. Keep sr/n_fft/fmin/fmax/htk identical to the values used by the forward transform so the round-trip stays consistent; a mel_spectrogram(...) or mfcc(...) result carries them as attributes.

istft reconstructs centered audio from matching magnitude and phase matrices shaped (n_bins, n_frames). If omitted, n_fft is inferred from the row count and hop_length defaults to max(1, n_fft // 4), and the result is a one-dimensional float32 waveform. A shape mismatch or zero length_samples is refused as SonareValueError; omit the length to use the natural output length.

python
import numpy as np
from libsonare import istft

waveform = istft(
    np.ones((65, 4), dtype=np.float32),
    np.zeros((65, 4), dtype=np.float32),
    n_fft=128,
    hop_length=32,
)
assert waveform.shape == (96,)
assert waveform.dtype == np.float32
python
# Reconstruct centered audio from STFT magnitude and phase matrices.
def istft(
    magnitude: npt.ArrayLike,
    phase: npt.ArrayLike,
    n_fft: int | None = None,
    hop_length: int | None = None,
    *,
    length_samples: int | None = None,
) -> np.ndarray: ...

Scale Quantization ​

12-TET scale helpers for building pitch-correction targets. mode_mask is a 12-bit mask where bit i enables the i-th pitch class relative to root (PitchClass, C = 0); natural major is 0b101010110101. scale_reference_midi is the tuning anchor (pass 0.0 for A4 = 69). Pair with pitch_correct_to_midi(...) to retune to the nearest scale degree.

python
# Return the 12-bit scale mask of a mode.
def scale_mask_for_mode(root: int, mode: KeyMode) -> int: ...

# Snap a (possibly fractional) MIDI number to the nearest enabled pitch class.
def scale_quantize_midi(
    root: int,
    mode_mask: int,
    midi: float,
    scale_reference_midi: float | None = None,
) -> float: ...

# Return the correction (quantized - input) in semitones.
def scale_correction_semitones(
    root: int,
    mode_mask: int,
    midi: float,
    scale_reference_midi: float | None = None,
) -> float: ...

# Return True if pitch_class (0..11) is enabled by mode_mask relative to root.
def scale_pitch_class_enabled(root: int, mode_mask: int, pitch_class: int) -> bool: ...
FunctionDescription
scale_mask_for_modeReturns the 12-bit mode mask. Pass a KeyMode string, for example "major", "minor" (natural minor), or "dorian". A non-string raises TypeError. An unknown string raises SonareValueError.
scale_quantize_midiSnap a (fractional) MIDI number to the nearest enabled pitch class
scale_correction_semitonesCorrection (quantized − input), in semitones
scale_pitch_class_enabledWhether pitch_class (0..11) is enabled relative to root

Conversion Functions ​

python
# Convert frequency in Hz to Mel scale.
def hz_to_mel(hz: float) -> float: ...

# Convert Mel scale value to frequency in Hz.
def mel_to_hz(mel: float) -> float: ...

# Convert frequency in Hz to MIDI note number.
def hz_to_midi(hz: float) -> float: ...

# Convert MIDI note number to frequency in Hz.
def midi_to_hz(midi: float) -> float: ...

# Convert frequency in Hz to note name (e.g.
def hz_to_note(hz: float) -> str: ...

# Convert note name (e.g.
def note_to_hz(note: str) -> float: ...

# Convert frame count to time in seconds.
def frames_to_time(frames: int, sr: int = 22050, hop_length: int = 512) -> float: ...

# Convert time in seconds to frame count.
def time_to_frames(time_sec: float, sr: int = 22050, hop_length: int = 512) -> int: ...

# Convert frame count to sample index.
def frames_to_samples(frames: int, hop_length: int = 512, n_fft: int | None = None) -> int: ...

# Convert sample index to frame count.
def samples_to_frames(samples: int, hop_length: int = 512, n_fft: int | None = None) -> int: ...

# Convert power values to dB; returns a float32 array shaped like ``values``.
def power_to_db(
    values: Sequence[float] | list[float],
    ref: float = 1.0,
    amin: float = 1e-10,
    top_db: float = 80.0,
) -> np.ndarray: ...

# Convert amplitude values to dB; returns a float32 array shaped like ``values``.
def amplitude_to_db(
    values: Sequence[float] | list[float],
    ref: float = 1.0,
    amin: float = 1e-05,
    top_db: float = 80.0,
) -> np.ndarray: ...

# Convert dB values back to power; returns a float32 array shaped like ``values``.
def db_to_power(values: Sequence[float] | list[float], ref: float = 1.0) -> np.ndarray: ...

# Convert dB values back to amplitude; returns a float32 array shaped like ``values``.
def db_to_amplitude(values: Sequence[float] | list[float], ref: float = 1.0) -> np.ndarray: ...
FunctionDescription
hz_to_melHertz → Mel scale
mel_to_hzMel scale → Hertz
hz_to_midiHertz → MIDI note number
midi_to_hzMIDI note number → Hertz
hz_to_noteHertz → note name (e.g., "A4"); SonareValueError if hz is not finite and positive
note_to_hzNote name → Hertz; SonareValueError if the name does not parse or its octave is outside -1 to 9
frames_to_timeFrame index → seconds
time_to_framesSeconds → frame index
frames_to_samplesFrame index → sample index (librosa.frames_to_samples)
samples_to_framesSample index → frame index (librosa.samples_to_frames)
power_to_dbPower → dB (librosa.power_to_db)
amplitude_to_dbAmplitude → dB (librosa.amplitude_to_db)
db_to_powerdB → power
db_to_amplitudedB → amplitude

Channel and signal utilities ​

python
# Decode audio bytes once and keep every source channel.
def decode_channels(data: bytes) -> DecodedChannels: ...

# Downmix channels to a narrower layout with the ITU-R BS.775 rule.
def downmix(
    channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
    target_layout: ChannelLayout,
    *,
    normalize: bool = False,
    include_lfe: bool = False,
) -> np.ndarray: ...

# Apply a cosine fade-in and fade-out to mono audio.
def fade(
    samples: Sequence[float] | list[float],
    sample_rate: int,
    *,
    fade_in_sec: float = 0.0,
    fade_out_sec: float = 0.0,
) -> np.ndarray: ...

# Filter mono audio with a biquad, or a cascade of two for order 4.
def biquad_filter(
    samples: Sequence[float] | list[float],
    sample_rate: int,
    *,
    type: BiquadFilterType,
    order: int = 2,
    zero_phase: bool = False,
    cutoff_hz: float | None = None,
    center_hz: float | None = None,
    bandwidth_hz: float | None = None,
) -> np.ndarray: ...
FunctionDescription
decode_channelsDecodes encoded audio bytes once and keeps every source channel as a channel-planar (num_channels, frames) float32 array, where Audio.from_memory folds a multichannel source to mono
downmixDownmixes channels to a narrower layout ("mono", "stereo", "5.1", "7.1") with the ITU-R BS.775 rule: center and surround enter the front pair at -3 dB and LFE is dropped unless include_lfe=True. The fold is not normalized unless normalize=True; an upmix is refused
fadeApplies a cosine fade-in and fade-out of fade_in_sec and fade_out_sec to mono audio; each length is clamped to the input and 0 leaves that end untouched
biquad_filterFilters mono audio with a biquad (a cascade of two for order=4). "highPass" and "lowPass" read cutoff_hz; "bandPass" and "notch" read center_hz and bandwidth_hz; a frequency the type does not read must be left None. zero_phase=True runs the filter forward and backward to cancel the phase shift

Unit Conversions ​

python
from libsonare import hz_to_mel, mel_to_hz, hz_to_midi, midi_to_hz
from libsonare import hz_to_note, note_to_hz, frames_to_time, time_to_frames

hz_to_mel(440.0)       # → 6.6 (Slaney mel scale)
mel_to_hz(6.6)         # → 440.0
hz_to_midi(440.0)      # → 69.0
midi_to_hz(69.0)       # → 440.0
hz_to_note(440.0)      # → "A4"
note_to_hz("A4")       # → 440.0

frames_to_time(100, sr=22050, hop_length=512)  # → seconds
time_to_frames(2.32, sr=22050, hop_length=512) # → frame index