Python Effects API
Audio effects and the effects functions of the libsonare Python package; room acoustics are on Python Room Acoustics API, and the realtime voice changer and streaming equalizer are on Python Streaming API. Framing, normalization and tempogram helpers are on Python Metering and Signal Helpers API, and note and percussive editing on Python Note Editing API. Installation, quick start, and the other API families are on the Python API index.
Audio Effects
from libsonare import Audio
audio = Audio.from_file("music.mp3")
# Harmonic-Percussive Source Separation
hpss_result = audio.hpss()
harmonic = audio.harmonic()
percussive = audio.percussive()
# Time stretch / pitch shift
stretched = audio.time_stretch(speed_ratio=1.5) # 1.5x speed
shifted = audio.pitch_shift(pitch_semitones=2.0) # Up 2 semitones
# Normalize and trim silence
normalized = audio.normalize(target_db=-3.0)
trimmed = audio.trim(threshold_db=-60.0)
# Resample
resampled = audio.resample(target_sample_rate=44100)For region-based time/frequency edits, use spectral_edit(samples, sample_rate, [SpectralRegionOp(...)]); see Spectral Editing.
# Region-based spectral editing (STFT -> per-op bin/frame masking -> iSTFT).
def spectral_edit(
samples: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
ops: Sequence[SpectralRegionOp],
*,
n_fft: int | None = None,
hop_length: int | None = None,
window: WindowType = 'hann',
heal_radius_frames: int | None = None,
) -> NDArray[np.float32]: ...Effects Functions
# Perform harmonic-percussive source separation.
def hpss(
samples: Sequence[float] | list[float],
sample_rate: int,
kernel_harmonic: int = 31,
kernel_percussive: int = 31,
n_fft: int = _DEFAULT_EFFECT_N_FFT,
hop_length: int | None = None,
hard_mask: bool = False,
with_residual: bool = False,
) -> HpssResult: ...
# Extract the harmonic component of audio.
def harmonic(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...
# Extract the percussive component of audio.
def percussive(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...
# Time-stretch audio without changing pitch.
def time_stretch(
samples: Sequence[float] | list[float],
sample_rate: int,
speed_ratio: float,
n_fft: int = _DEFAULT_EFFECT_N_FFT,
hop_length: int | None = None,
) -> np.ndarray: ...
# Shift the pitch of audio.
def pitch_shift(
samples: Sequence[float] | list[float],
sample_rate: int,
pitch_semitones: float,
n_fft: int = _DEFAULT_EFFECT_N_FFT,
hop_length: int | None = None,
) -> np.ndarray: ...| Function | Description |
|---|---|
hpss | Harmonic-Percussive Source Separation; defaults: kernel_harmonic=31, kernel_percussive=31, n_fft=2048, hop_length=None (a quarter of n_fft), hard_mask=False; with_residual=True also fills residual |
harmonic | Extract harmonic component |
percussive | Extract percussive component |
time_stretch | Time-stretch without pitch change; defaults: n_fft=2048, hop_length=None (a quarter of n_fft) |
pitch_shift | Pitch-shift without tempo change; defaults: n_fft=2048, hop_length=None (a quarter of n_fft) |
# Pitch-correct audio from a current MIDI note to a target MIDI note.
def pitch_correct_to_midi(
samples: Sequence[float] | list[float],
sample_rate: int,
current_midi: float,
target_midi: float,
) -> np.ndarray: ...
# Contour-following pitch correction toward a fixed MIDI note OR a scale.
def pitch_correct_timevarying(
samples: Sequence[float] | list[float],
sample_rate: int,
f0_hz: Sequence[float] | list[float],
hop_length: int = 512,
*,
target_mode: PitchTargetMode = 'midi',
target_midi: float = 69.0,
scale_root: int = 0,
scale_mode_mask: int | KeyMode | None = None,
scale_reference_midi: float | None = None,
retune_amount: float | None = None,
max_correction_semitones: float | None = None,
retune_speed_ms: float | None = None,
vibrato_threshold_cents: float | None = None,
voiced: Sequence[int] | list[int] | None = None,
voiced_prob: Sequence[float] | list[float] | None = None,
) -> np.ndarray: ...
# Snap the voiced pitch of a monophonic recording to a scale, offline.
def auto_tune(
samples: Sequence[float] | list[float],
sample_rate: int,
key: str | Key | Mapping[str, object] | tuple[PitchClass, KeyMode] = 'detect',
*,
retune_amount: float | None = None,
retune_speed_ms: float | None = None,
vibrato_threshold_cents: float | None = None,
max_correction_semitones: float | None = None,
scale_reference_midi: float | None = None,
) -> AutoTuneResult: ...
# Apply a voice-change effect with independent pitch and formant control.
def voice_change(
samples: Sequence[float] | list[float],
sample_rate: int,
pitch_semitones: float = 0.0,
formant_factor: float = 1.0,
formant_mode: FormantMode = 'relative',
) -> np.ndarray: ...
# Apply the realtime voice changer to a buffer offline.
def realtime_voice_changer_render(
samples: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
*,
config: VoicePresetId | RealtimeVoiceChangerPreset | RealtimeVoiceChangerConfig | None = 'neutralMonitor',
num_channels: int = 1,
) -> np.ndarray: ...| Function | Description |
|---|---|
pitch_correct_to_midi | Pitch-correct toward a target MIDI note |
pitch_correct_timevarying | Contour-following pitch correction: retunes every voiced frame along a per-frame f0_hz contour, preserving vibrato and drift instead of flattening it. It corrects toward a fixed note (target_mode="midi") or the nearest degree of a scale (target_mode="scale"); scale_mode_mask takes a 12-bit integer mask or a KeyMode string when in scale mode. None selects C major. The retune knobs trade natural for robotic correction |
auto_tune | Tune a monophonic take to a detected ("detect") or named key (Key, {"root", "mode"} or (root, mode)); .samples is the tuned audio and .key the key used |
voice_change | Independent pitch + formant shift. formant_mode is "relative" (default: formant_factor is a warp in [0.55, 1.65] applied after the pitch shift) or "absolute" (formant_factor is the formant shift relative to the input whatever the pitch shift; 1.0 keeps the formants in place). A relative factor outside that range, and an absolute request whose warp formant_factor / 2**(pitch_semitones / 12) leaves it, raise SonareValueError naming the reachable formant_factor range |
realtime_voice_changer_render | One-shot render through the realtime voice preset chain; config is a preset id, a configuration mapping or a RealtimeVoiceChangerConfig, and two channels are interleaved |
# Time-stretch a single note region without changing pitch.
def note_stretch(
samples: Sequence[float] | list[float],
sample_rate: int,
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 to a new onset without changing its duration.
def note_move(
samples: Sequence[float] | list[float],
sample_rate: int,
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: ...| Function | Description |
|---|---|
note_stretch | Stretch a single note region in place |
note_move | Move a note region to a new onset without changing its duration; provide exactly one of target_onset_sample and target_onset_sec |
# Normalize audio so its peak or RMS level reaches ``target_db``.
def normalize(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
mode: NormalizeMode = 'peak',
target_db: float | None = None,
) -> np.ndarray: ...
# Normalize a stereo pair on one gain measured across both channels.
def normalize_stereo(
left: Sequence[float] | list[float] | np.ndarray,
right: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
*,
mode: NormalizeMode = 'peak',
target_db: float | None = None,
) -> NormalizeStereoResult: ...
# Reorder / concatenate a signal by interval slices (librosa.effects.remix).
def remix(
samples: Sequence[float] | list[float],
intervals: npt.ArrayLike,
sr: int = 22050,
align_zeros: bool = True,
) -> np.ndarray: ...
# Resolve the cut points :func:`remix` would use, without cutting.
def remix_aligned_intervals(
samples: Sequence[float] | list[float],
sample_rate: int,
intervals: npt.ArrayLike,
align_zeros: bool = True,
) -> np.ndarray: ...
# Trim silence from the beginning and end of audio.
def trim(
samples: Sequence[float] | list[float],
sample_rate: int,
threshold_db: float = -60.0,
frame_length: int = _DEFAULT_TRIM_FRAME_LENGTH,
hop_length: int = _DEFAULT_TRIM_HOP_LENGTH,
) -> np.ndarray: ...
# Resample audio to a different sample rate.
def resample(
samples: Sequence[float] | list[float],
sample_rate: int,
target_sample_rate: int,
) -> np.ndarray: ...| Function | Description |
|---|---|
normalize | Normalize to a target level; mode is "peak" (default, target_db default 0.0) or "rms" (target_db default -20.0) |
normalize_stereo | Normalize a pair on one shared gain; mode and target_db as for normalize |
remix | Reorder/concatenate by (n, 2) interval slices; align_zeros default True |
remix_aligned_intervals | Resolve the cut points remix would use, without cutting; align_zeros default True |
trim | Trim silence (defaults: -60.0 dB, frame_length=2048, hop_length=512) |
resample | Resample to target sample rate |
Every edit position takes samples or seconds (*_sec), never both; giving both is refused. SpectralRegionOp likewise takes start_sec / end_sec.
trim(...) is the simple threshold-based edit helper. The trim_silence(...) helper on Python Metering and Signal Helpers API uses frame RMS and top_db, and returns the trimmed audio together with its original sample range.
Normalizing a stereo pair
normalize_stereo(...) takes a mode ("peak" or "rms"), as the JavaScript surfaces do. It measures the level across the pair and applies one shared gain to both channels, which is what keeps the stereo image intact: normalizing each channel on its own gain would lift the quieter side until the two peaks matched, changing the balance rather than the level. An all-silent pair raises SonareValueError. Floating-point output can exceed full scale. Alongside left and right the result carries length, the pair's shared sample count.
Either channel empty, or the two channels unequal in length, is refused. The C entry takes one sample rate for the pair, so the two channels cannot disagree on it.
result = sonare.normalize_stereo(left, right, 48000, target_db=-3.0)
print(result.length)Cutting a multichannel take on one frame set
remix(...) snaps slice boundaries (its align_zeros defaults to True) to the signal's zero-crossings, which is a per-signal decision: calling remix channel by channel snaps each channel to a different frame and drifts a stereo take apart. remix_aligned_intervals(...) resolves one cut set from one channel — an (n, 2) array of clamped (start, end) rows — so you can slice every channel with the same frames by passing align_zeros=False to remix.
Two guards stop a slice from vanishing under snapping: a signal with no sign change at all (silence, a DC offset, any constant) is not snapped, and a slice that had content but would collapse to empty keeps its unsnapped boundaries.
cuts = sonare.remix_aligned_intervals(left, 48000, [(0, 48000), (96000, 144000)])
left_out = sonare.remix(left, cuts, sr=48000, align_zeros=False)
right_out = sonare.remix(right, cuts, sr=48000, align_zeros=False)