Audio helpers¶
from interactive_pipe import sound — pure numpy functions to load, analyse
and transform 1D audio signals inside filters; play the result with the
audio proxy. See Audio
for an example and demo/audio_processing_demo.py for a complete app.
Small audio toolbox for interactive pipelines: load, analyse, denoise, pitch-shift.
Dependency-free (numpy and the standard library; ffmpeg is used only to
decode compressed files such as .mp3 / .mp4 when it is installed).
Meant to be called inside filters, next to the audio proxy that plays
the result::
from interactive_pipe import audio, interactive, layout, sound
@interactive(semitones=(0.0, [-12.0, 12.0]))
def shift(signal, semitones=0.0):
out = sound.pitch_shift(signal, semitones)
audio.set(out, 16000)
audio.play()
return out
@interactive()
def show(signal):
layout.style("spec", **sound.spectrogram_style(signal, 16000))
return sound.spectrogram(signal)
Conventions shared by every function:
- Signals are 1D float arrays in
[-1, 1](mono).loadreturns mono by default; the processing functions take mono only. - Pure: the input is never modified; a new
float32array is returned, of the same length unless the function says otherwise. - STFT frames use a Hann window,
n_fftsamples,hopsamples apart (defaultn_fft // 4), and reconstruct exactly (istft(stft(x)) == xup to float error).
load
¶
load(path: PathLike, sample_rate: Optional[int] = None, mono: bool = True, start: float = 0.0, duration: Optional[float] = None) -> Tuple[np.ndarray, int]
Read an audio file as (signal, sample_rate), float32 in [-1, 1].
WAV files (8, 16, 24 or 32-bit PCM) are read with the standard library;
any other format (.mp3, .mp4, .flac, .ogg...) is decoded
with ffmpeg when it is on the PATH.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The file. |
required |
sample_rate
|
Optional[int]
|
Resample to this rate (Hz); |
None
|
mono
|
bool
|
Average the channels (shape |
True
|
start
|
float
|
Skip this many seconds. |
0.0
|
duration
|
Optional[float]
|
Keep at most this many seconds; |
None
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The file does not exist. |
RuntimeError
|
Not a WAV file and |
ValueError
|
Unsupported WAV sample width. |
Source code in src/interactive_pipe/sound.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
to_mono
¶
to_mono(signal: ndarray) -> np.ndarray
Average the channels of a (n, channels) signal; a 1D signal is returned as float32.
Source code in src/interactive_pipe/sound.py
179 180 181 182 | |
normalize
¶
normalize(signal: ndarray, peak: float = 0.9) -> np.ndarray
Scale so that the largest absolute value is peak (a silent signal is returned unchanged).
Source code in src/interactive_pipe/sound.py
185 186 187 188 189 | |
resample
¶
resample(signal: ndarray, rate_in: float, rate_out: float) -> np.ndarray
Change the sampling rate (band-limited, by zero-padding or cropping the spectrum).
Source code in src/interactive_pipe/sound.py
192 193 194 195 196 | |
stft
¶
stft(signal: ndarray, n_fft: int = 1024, hop: Optional[int] = None) -> np.ndarray
Complex STFT, shape (frames, n_fft // 2 + 1) (one row per frame, low frequencies first).
The signal is padded by n_fft // 2 on both sides so that frame i
is centred on sample i * hop.
Source code in src/interactive_pipe/sound.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |
istft
¶
istft(spectrum: ndarray, hop: Optional[int] = None, length: Optional[int] = None) -> np.ndarray
Inverse of :func:stft (weighted overlap-add); length crops to the original signal length.
Source code in src/interactive_pipe/sound.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
spectrogram
¶
spectrogram(signal: ndarray, n_fft: int = 512, hop: Optional[int] = None, floor_db: float = -80.0) -> np.ndarray
Log-magnitude spectrogram in dB, ready to display as a heatmap.
Shape (n_fft // 2 + 1, frames): time runs left to right and low
frequencies are at the bottom (row 0 is the Nyquist frequency), as on
any spectrogram plot. 0 dB is a full-scale sine; values below
floor_db are clipped. Pair it with :func:spectrogram_style for the
colormap and the time / frequency axes.
Source code in src/interactive_pipe/sound.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
spectrogram_style
¶
spectrogram_style(signal: ndarray, sample_rate: int, floor_db: float = -80.0, colormap: str = 'magma', title: Optional[str] = None) -> dict
Keyword arguments for layout.style(name, **...) matching :func:spectrogram.
Time axis in seconds, frequency axis in kHz, a dB colour bar.
Source code in src/interactive_pipe/sound.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
add_noise
¶
add_noise(signal: ndarray, snr: float = 10.0, kind: str = 'white', sample_rate: int = 16000, seed: int = 0) -> Tuple[np.ndarray, np.ndarray]
Add noise at a given signal-to-noise ratio (dB); returns (noisy, noise).
Kinds: "white" (flat spectrum), "pink" (1/f, louder in the
lows, like wind or a fan), "hum" (50 Hz mains and its harmonics plus
a little hiss; uses sample_rate). Deterministic for a given seed.
Source code in src/interactive_pipe/sound.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
snr_db
¶
snr_db(reference: ndarray, estimate: ndarray) -> float
Signal-to-noise ratio of estimate against reference in dB (inf when identical).
Source code in src/interactive_pipe/sound.py
347 348 349 350 351 352 353 | |
denoise
¶
denoise(signal: ndarray, strength: float = 1.5, max_attenuation_db: float = 30.0, noise: Optional[ndarray] = None, n_fft: int = 1024, smoothing: int = 3) -> np.ndarray
Remove stationary noise (hiss, hum, fan) by spectral gating.
Each time-frequency bin is attenuated by how much of it the noise
explains: gain = 1 - strength * noise_level / level, limited to
-max_attenuation_db and smoothed over smoothing frames and bins
(fewer "musical noise" chirps).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
ndarray
|
The noisy signal. |
required |
strength
|
float
|
Over-subtraction factor: 0 does nothing, 1 subtracts the noise estimate, more removes more noise (and more signal). |
1.5
|
max_attenuation_db
|
float
|
Deepest cut in dB; a floor keeps a natural residual instead of holes. |
30.0
|
noise
|
Optional[ndarray]
|
A noise-only recording (any length) to take the noise
spectrum from. |
None
|
n_fft
|
int
|
STFT size; larger resolves hum lines better, smaller smears less in time. |
1024
|
smoothing
|
int
|
Width (frames and bins) of the gain smoothing, 1 for none. |
3
|
Source code in src/interactive_pipe/sound.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
time_stretch
¶
time_stretch(signal: ndarray, factor: float, n_fft: int = 1024) -> np.ndarray
Make the signal factor times longer without changing its pitch (phase vocoder).
factor=2 plays twice as slow, 0.5 twice as fast; the output has
about factor * len(signal) samples.
Source code in src/interactive_pipe/sound.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
pitch_shift
¶
pitch_shift(signal: ndarray, semitones: float, n_fft: int = 1024) -> np.ndarray
Raise (or lower, negative) the pitch by semitones keeping the duration.
Phase-vocoder stretch by 2 ** (semitones / 12) then resampling back
to the original length. Formants move with the pitch: +12 sounds like a
chipmunk, -12 like a giant. n_fft 1024 suits 16-22 kHz audio
(2048 at 44.1 kHz).
Source code in src/interactive_pipe/sound.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |