Spectral Analysis

The spectral pipeline: STFT and inverse STFT, dB conversions, the mel filterbank, MFCCs and delta features.

Two entry points are provided:

  • methods on audio_samples.AudioSamples, which analyse every channel and always return arrays shaped (channels, n_features, n_frames) (mono audio gives a leading axis of length 1; index [0] for the (n_features, n_frames) array);

  • free functions in audio_samples.spectral over NumPy arrays: a 1-D signal gives a 2-D result and a (channels, n) signal a 3-D result.

Windows are given as SciPy-style specifications: "hann" (default), "hamming", "blackman", "blackmanharris", "boxcar" / "rectangular", "bartlett", "triang", ("kaiser", beta), ("gaussian", std), a number (Kaiser beta) or an array of coefficients.

AudioSamples methods

AudioSamples.stft_matrix(*, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Complex short-time Fourier transform of every channel.

Parameters:
  • n_fft (int) – FFT length in samples. Default 2048.

  • hop_length (Optional[int]) – Samples between frames. None means win_length // 4.

  • win_length (Optional[int]) – Window length (<= n_fft); None means n_fft. Shorter windows are zero-padded to n_fft.

  • window (str | tuple | numpy.ndarray) – Window specification, as scipy.signal.get_window: "hann" (default), "hamming", "blackman", "blackmanharris", "boxcar"/"rectangular", "bartlett", "triang", ("kaiser", beta), ("gaussian", std), or an array of win_length coefficients. Named windows are periodic (fftbins=True).

  • center (bool) – Pad by n_fft // 2 on both sides so frame t is centred on sample t * hop_length. Default True.

  • pad_mode (str) – "constant" (zeros, default), "reflect", "edge" or "symmetric".

Returns:

shape (channels, 1 + n_fft // 2, n_frames); complex64 for uint8, int16, int24 and float32 audio, complex128 for int32 and float64 audio. Mono audio gives a leading axis of length 1 (index [0] for (1 + n_fft // 2, n_frames)).

Return type:

numpy.ndarray[complex64 | complex128]

Raises:

ValueError – For invalid parameters, or center=False with a signal shorter than n_fft.

static AudioSamples.istft_matrix(stft_matrix, *, sample_rate, hop_length=None, win_length=None, n_fft=None, window='hann', center=True, length=None, dtype=None)

Reconstruct audio from an STFT matrix by weighted overlap-add.

This is a static method: AudioSamples.istft_matrix(D, sample_rate=sr).

Parameters:
  • stft_matrix (array_like) – complex array of shape (channels, 1 + n_fft // 2, n_frames) or (1 + n_fft // 2, n_frames) (treated as one channel).

  • sample_rate (int) – Sample rate of the returned audio (keyword-only).

  • hop_length (Optional[int]) – None means win_length // 4.

  • win_length (Optional[int]) – None means n_fft.

  • n_fft (Optional[int]) – None infers 2 * (n_bins - 1).

  • window – Window used for analysis (see stft_matrix).

  • center (bool) – Whether the analysis frames were centred.

  • length (Optional[int]) – Exact output length per channel; pass the original length to undo the centre padding exactly.

  • dtype (Optional[SampleType]) – Sample type of the returned audio. None (default) gives float32 audio for a complex64 matrix and float64 audio for any other input. The inverse transform runs in the float type of dtype (float32 for U8, I16, I24 and F32; float64 for I32 and F64); integer output is rounded and saturated.

Returns:

audio of sample type dtype, mono for a single channel.

Return type:

AudioSamples

Raises:

ValueError – If the matrix is not 2-D/3-D, the bin count does not match n_fft, or parameters are invalid.

AudioSamples.spectrogram_matrix(*, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant', power=1.0)

Magnitude spectrogram |STFT| ** power of every channel.

Equivalent to numpy.abs(self.stft_matrix(...)) ** power.

Parameters:
  • n_fft – As stft_matrix.

  • hop_length – As stft_matrix.

  • win_length – As stft_matrix.

  • window – As stft_matrix.

  • center – As stft_matrix.

  • pad_mode – As stft_matrix.

  • power (float) – Exponent; 1.0 (default) gives magnitude, 2.0 power.

Returns:

shape (channels, 1 + n_fft // 2, n_frames); float32 for uint8, int16, int24 and float32 audio, float64 for int32 and float64 audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a non-positive power.

AudioSamples.melspectrogram(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', power=2.0, n_mels=128, fmin=0.0, fmax=None, htk=False, norm='slaney')

Mel spectrogram of every channel: the mel filterbank applied to the STFT magnitude raised to power.

Parameters:
  • n_fft (int) – Default 2048.

  • hop_length (int) – Default 512.

  • win_length – As stft_matrix.

  • window – As stft_matrix.

  • center – As stft_matrix.

  • pad_mode – As stft_matrix.

  • power (float) – Exponent of the STFT magnitude; 2.0 (default) for power, 1.0 for magnitude.

  • n_mels (int) – Number of mel bands. Default 128.

  • fmin (float) – Lowest frequency (Hz). Default 0.

  • fmax (Optional[float]) – Highest frequency (Hz); None = sr / 2.

  • htk (bool) – HTK mel scale instead of Slaney (default False).

  • norm (None | "slaney" | float) – Filter normalisation. Default “slaney”.

Returns:

shape (channels, n_mels, n_frames); float32 for uint8, int16, int24 and float32 audio, float64 for int32 and float64 audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.mfcc_frames(*, n_mfcc=20, dct_type=2, norm='ortho', lifter=0.0, mel_norm='slaney', n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', power=2.0, n_mels=128, fmin=0.0, fmax=None, htk=False, ref=1.0, amin=1e-10, top_db=None)

Mel-frequency cepstral coefficients of every channel.

The pipeline is melspectrogram -> power_to_db(ref, amin, top_db) -> DCT along the mel axis -> first n_mfcc rows -> optional liftering.

Parameters:
  • n_mfcc (int) – Number of coefficients. Default 20.

  • dct_type (int) – 1, 2 (default) or 3.

  • norm (Optional[str]) – DCT normalisation, "ortho" (default) or None.

  • lifter (float) – Liftering coefficient (0 disables). Default 0.

  • mel_norm (None | "slaney" | float) – Mel filter normalisation (norm of melspectrogram). Default “slaney”.

  • n_fft (default 512)

  • hop_length (default 512)

  • power – Passed to the mel spectrogram, as in melspectrogram.

  • n_mels – Passed to the mel spectrogram, as in melspectrogram.

  • fmin – Passed to the mel spectrogram, as in melspectrogram.

  • fmax – Passed to the mel spectrogram, as in melspectrogram.

  • htk – Passed to the mel spectrogram, as in melspectrogram.

  • ref (float | "max" | numpy.max) – dB reference. Default 1.0.

  • amin (float) – dB floor before the log. Default 1e-10.

  • top_db (Optional[float]) – Dynamic range floor in dB below the peak (per channel). Default None (no floor).

Returns:

shape (channels, n_mfcc, n_frames); float32 for uint8, int16, int24 and float32 audio, float64 for int32 and float64 audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters, including n_mfcc > n_mels.

Array functions (audio_samples.spectral)

Spectral functions over NumPy arrays (STFT/ISTFT, dB conversions, mel filterbank, windows, delta, stack_memory, frame). float32 / complex64 arrays are processed in float32 and give float32 output; any other input is converted to float64.

Transforms

audio_samples.spectral.stft(y, *, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Short-time Fourier transform.

Parameters:
  • y (numpy.ndarray) – Real signal, shape (n,) or (channels, n).

  • n_fft (int) – FFT length. Default 2048.

  • hop_length (Optional[int]) – None means win_length // 4.

  • win_length (Optional[int]) – None means n_fft.

  • window – Window name, (name, param) tuple or coefficient array (see get_window). Default "hann".

  • center (bool) – Centre frames (pad n_fft // 2 each side). Default True.

  • pad_mode (str) – "constant" (default), "reflect", "edge", "symmetric".

Returns:

shape (1 + n_fft // 2, n_frames) for 1-D input, (channels, 1 + n_fft // 2, n_frames) for 2-D input.

Return type:

numpy.ndarray[complex64 | complex128]

Raises:

ValueError – For invalid parameters or input with more than 2 dimensions.

audio_samples.spectral.istft(stft_matrix, *, hop_length=None, win_length=None, n_fft=None, window='hann', center=True, length=None)

Inverse short-time Fourier transform by weighted overlap-add.

Parameters:
  • stft_matrix (array_like) – complex array of shape (1 + n_fft // 2, n_frames) or (channels, 1 + n_fft // 2, n_frames).

  • hop_length (Optional[int]) – None means win_length // 4.

  • win_length (Optional[int]) – None means n_fft.

  • n_fft (Optional[int]) – None infers 2 * (n_bins - 1).

  • window – As in stft.

  • center (bool) – Whether the frames were centred. Default True.

  • length (Optional[int]) – Exact output length.

Returns:

shape (n,) for 2-D input, (channels, n) for 3-D.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a bin count that does not match n_fft.

audio_samples.spectral.frame(x, *, frame_length, hop_length, copy=True)

Slice a 1-D signal into overlapping frames along the last axis.

By default the frames are a new, writable array (a copy). With copy=False the result is instead a read-only strided view into x: no data is copied, the view keeps x alive and reflects later changes to it. Input that is not a contiguous float32 / float64 array is converted first, and the view is into the converted array.

Parameters:
  • x (array_like) – 1-D signal.

  • frame_length (int) – Samples per frame.

  • hop_length (int) – Samples between frame starts.

  • copy (bool) – Return a writable copy (default) or, if False, a read-only view into x.

Returns:

shape (frame_length, 1 + (len(x) - frame_length) // hop_length).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – If x is not 1-D or is shorter than frame_length, or (copy only) the frame matrix would exceed 2^31 elements.

Decibel conversions

audio_samples.spectral.power_to_db(S, *, ref=1.0, amin=1e-10, top_db=None, axes='auto')

Convert a power spectrogram to decibels.

Computes 10 * log10(max(amin, S)) - 10 * log10(max(amin, |ref|)), floored at max - top_db.

Parameters:
  • S (array_like) – Power values, any shape (or a scalar).

  • ref (float | "max" | numpy.max) – 0 dB reference. Default 1.0.

  • amin (float) – Lower clamp before the log. Default 1e-10.

  • top_db (Optional[float]) – Dynamic range below the maximum. Default None (no floor).

  • axes ("auto" | None) – Reduction axes for ref=numpy.max and top_db. "auto" (default) uses the last two axes, i.e. per channel for (channels, F, T) input; None uses the whole array.

Returns:

Same shape as S.

Return type:

float | numpy.ndarray[float32 | float64]

Raises:
  • ValueError – If amin <= 0 or top_db < 0.

  • TypeError – For complex input (pass power, e.g. numpy.abs(D) ** 2).

audio_samples.spectral.amplitude_to_db(S, *, ref=1.0, amin=1e-05, top_db=None, axes='auto')

Convert an amplitude spectrogram to decibels.

20 * log10(max(amin, |S|) / max(amin, |ref|)), floored at max - top_db. Complex input is replaced by its magnitude.

Parameters:
  • S (array_like) – Amplitudes (real or complex), any shape.

  • ref (float | "max" | numpy.max) – 0 dB reference. Default 1.0.

  • amin (float) – Lower clamp. Default 1e-5.

  • top_db (Optional[float]) – Dynamic range below the maximum. Default None (no floor).

  • axes ("auto" | None) – As power_to_db.

Returns:

Same shape as S.

Return type:

float | numpy.ndarray[float32 | float64]

Raises:

ValueError – If amin <= 0 or top_db < 0.

audio_samples.spectral.db_to_power(S_db, *, ref=1.0)

Convert decibels to power: ref * 10 ** (S_db / 10).

Parameters:
  • S_db (array_like) – dB values, any shape (or a scalar).

  • ref (float) – Reference power. Default 1.0.

Returns:

Same shape as S_db.

Return type:

float | numpy.ndarray[float32 | float64]

audio_samples.spectral.db_to_amplitude(S_db, *, ref=1.0)

Convert decibels to amplitude: sqrt(ref ** 2 * 10 ** (S_db / 10)).

Parameters:
  • S_db (array_like) – dB values, any shape (or a scalar).

  • ref (float) – Reference amplitude. Default 1.0.

Returns:

Same shape as S_db.

Return type:

float | numpy.ndarray[float32 | float64]

Filterbanks and windows

audio_samples.spectral.mel_filterbank(*, sr, n_fft, n_mels=128, fmin=0.0, fmax=None, htk=False, norm='slaney')

Mel filterbank matrix mapping STFT bins to mel bands (float64).

Parameters:
  • sr (float) – Sample rate (Hz).

  • n_fft (int) – FFT length.

  • n_mels (int) – Number of bands. Default 128.

  • fmin (float) – Lowest edge (Hz). Default 0.

  • fmax (Optional[float]) – Highest edge (Hz); None = sr / 2.

  • htk (bool) – HTK mel scale instead of Slaney. Default False.

  • norm (None | "slaney" | float) – "slaney" (default, area normalisation), None, or a p-norm (numpy.inf allowed).

Returns:

shape (n_mels, 1 + n_fft // 2).

Return type:

numpy.ndarray[float64]

Raises:

ValueError – For invalid parameters (e.g. fmax <= fmin).

audio_samples.spectral.get_window(window, Nx, *, fftbins=True)

Window coefficients for a window specification.

Parameters:
  • window – "hann", "hamming", "blackman", "blackmanharris", "boxcar" ("rectangular"), "bartlett", "triang", ("kaiser", beta), ("gaussian", std), a number (Kaiser beta), or an array of length Nx (returned as given).

  • Nx (int) – Window length.

  • fftbins (bool) – Periodic window (True, default) or symmetric (False).

Returns:

shape (Nx,).

Return type:

numpy.ndarray[float64]

Raises:

ValueError – Unknown window, invalid parameter, or an array of the wrong length.

audio_samples.spectral.window_sumsquare(*, window, n_frames, hop_length=512, win_length=None, n_fft=2048, norm=None, dtype=None)

Sum-squared window envelope of an overlap-add of n_frames windows.

Parameters:
  • window – Window specification (see get_window).

  • n_frames (int) – Number of frames.

  • hop_length (int) – Default 512.

  • win_length (Optional[int]) – None means n_fft.

  • n_fft (int) – Default 2048.

  • norm (Optional[float]) – Normalise the window before squaring, as features.normalize(w, norm=norm): None (default), a positive number (L-p norm), math.inf / -math.inf (max / min absolute value) or 0 (count of non-zeros).

  • dtype (Optional[numpy.dtype]) – float32 or float64. None (default) means float64.

Returns:

shape (n_fft + hop_length * (n_frames - 1),).

Return type:

numpy.ndarray[float64 | float32]

Raises:

ValueError – For invalid parameters.

audio_samples.spectral.window_bandwidth(window, n=1000)

Equivalent noise bandwidth of a window in FFT bins: n * sum(w ** 2) / sum(w) ** 2 for the periodic window of length n. The definition is evaluated for every window, named or not.

Parameters:
  • window – Window specification (see get_window).

  • n (int) – Window length. Default 1000.

Returns:

Bandwidth in bins (1.0 for boxcar, 1.5 for Hann).

Return type:

float

Features from spectrograms

audio_samples.spectral.melspectrogram_from_spectrogram(S, *, sr, n_fft=None, n_mels=128, fmin=0.0, fmax=None, htk=False, norm='slaney')

Project a spectrogram onto mel bands: the mel filterbank applied to S.

Parameters:
  • S (array_like) – Non-negative spectrogram, shape (1 + n_fft // 2, T) or (channels, 1 + n_fft // 2, T) (power or magnitude, as you choose).

  • sr (float) – Sample rate (Hz).

  • n_fft (Optional[int]) – FFT length; None infers 2 * (F - 1).

  • n_mels – As mel_filterbank.

  • fmin – As mel_filterbank.

  • fmax – As mel_filterbank.

  • htk – As mel_filterbank.

  • norm – As mel_filterbank.

Returns:

shape (n_mels, T) or (channels, n_mels, T).

Return type:

numpy.ndarray[float32 | float64]

audio_samples.spectral.mfcc_from_mel_db(S, *, n_mfcc=20, dct_type=2, norm='ortho', lifter=0.0)

MFCCs from a log-power (dB) mel spectrogram: DCT along the mel axis, first n_mfcc rows, liftering.

Parameters:
  • S (array_like) – dB mel spectrogram, shape (..., n_mels, T) (at least 2-D).

  • n_mfcc (int) – Default 20 (must not exceed n_mels).

  • dct_type (int) – 1, 2 (default) or 3.

  • norm (Optional[str]) – "ortho" (default) or None.

  • lifter (float) – Liftering coefficient; 0 (default) disables.

Returns:

shape (..., n_mfcc, T).

Return type:

numpy.ndarray[float32 | float64]

audio_samples.spectral.delta(data, *, width=9, order=1, axis=-1, mode='interp')

Savitzky-Golay delta features along the last axis.

Parameters:
  • data (array_like) – Feature array, any shape (e.g. (n_mfcc, T) or (channels, n_mfcc, T)).

  • width (int) – Odd window width >= 3. Default 9.

  • order (int) – Derivative order (1 = delta, 2 = delta-delta). Default 1.

  • axis (int) – Axis to differentiate along. Default -1.

  • mode (str) – "interp" (default), "nearest", "mirror", "constant" or "wrap".

Returns:

Same shape as data.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – Invalid width/order/axis, or mode="interp" with width larger than the axis.

audio_samples.spectral.stack_memory(data, *, n_steps=2, delay=1)

Stack time-delayed copies of a feature array (zero padding).

Parameters:
  • data (array_like) – shape (..., d, t); 1-D input is treated as (1, t).

  • n_steps (int) – Number of copies. Default 2.

  • delay (int) – Frame delay between copies (non-zero; negative looks ahead). Default 1.

Returns:

shape (..., d * n_steps, t).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – If n_steps < 1 or delay == 0.

Unit conversions (audio_samples.utils)

Vectorised: a scalar gives a Python number, an array-like gives a NumPy array of the same shape. hz_to_mel, mel_to_hz and mel_frequencies use the HTK scale by default; pass htk=False for the Slaney scale. time_to_frames rounds to the nearest frame; time_to_frames_floor gives the frame containing each time.

audio_samples.utils.hz_to_mel(freq_hz, *, htk=True)

Converts frequencies in Hertz to mels (scalar or array).

The default scale is HTK (2595 * log10(1 + f / 700)). Pass htk=False for the Slaney scale (linear below 1 kHz, logarithmic above), as used by spectral.mel_filterbank.

Parameters:
  • freq_hz (float | array_like) – Frequency or frequencies in Hertz.

  • htk (bool) – Use the HTK scale (default True) or the Slaney scale (False).

Returns:

Mels, same shape as the input.

Return type:

float | numpy.ndarray[float64]

Example

>>> from audio_samples.utils import hz_to_mel
>>> hz_to_mel(1000.0)              # HTK: ~999.99
>>> hz_to_mel(1000.0, htk=False)   # Slaney: 15.0
audio_samples.utils.mel_to_hz(mel, *, htk=True)

Converts mels to frequencies in Hertz (scalar or array).

The default scale is HTK; htk=False gives the Slaney scale.

Parameters:
  • mel (float | array_like) – Mel value(s).

  • htk (bool) – HTK scale (default True) or Slaney (False).

Returns:

Frequencies in Hertz, same shape as the input.

Return type:

float | numpy.ndarray[float64]

Example

>>> from audio_samples.utils import mel_to_hz
>>> mel_to_hz(15.0, htk=False)  # 1000.0
audio_samples.utils.mel_frequencies(n_mels, fmin, fmax, *, htk=True)

Frequencies uniformly spaced on the mel scale.

The default scale is HTK; pass htk=False for the Slaney scale.

Parameters:
  • n_mels (int) – Number of frequencies.

  • fmin (float) – Lowest frequency in Hertz.

  • fmax (float) – Highest frequency in Hertz.

  • htk (bool) – HTK scale (default True) or Slaney (False).

Returns:

shape (n_mels,), in Hertz.

Return type:

numpy.ndarray[float64]

Example

>>> from audio_samples.utils import mel_frequencies
>>> mel_frequencies(128, 0.0, 11025.0, htk=False)  # 128 Slaney-spaced frequencies
audio_samples.utils.hz_to_midi(freq_hz)

Converts frequencies in Hertz to (fractional) MIDI note numbers: 12 * log2(f / 440) + 69.

Parameters:

freq_hz (float | array_like) – Frequency or frequencies in Hertz.

Returns:

MIDI numbers, same shape as the input.

Return type:

float | numpy.ndarray[float64]

Example

>>> from audio_samples.utils import hz_to_midi
>>> hz_to_midi(440.0)  # 69.0
audio_samples.utils.midi_to_hz(midi_note)

Converts MIDI note numbers (fractional allowed) to Hertz: 440 * 2 ** ((m - 69) / 12).

Parameters:

midi_note (float | array_like) – MIDI number(s).

Returns:

Frequencies in Hertz, same shape as the input.

Return type:

float | numpy.ndarray[float64]

Example

>>> from audio_samples.utils import midi_to_hz
>>> midi_to_hz(69.0)  # 440.0
audio_samples.utils.time_to_samples(times, *, sample_rate=None, sr=None)

Converts times in seconds to sample indices.

int(t * sample_rate) truncated toward zero (negative times stay negative). Differs from seconds_to_samples, which rounds.

Parameters:
  • times (float | array_like) – Time(s) in seconds.

  • sample_rate (Optional[float]) – Sampling rate in Hertz. Give this or sr (exactly one).

  • sr (Optional[float]) – Short name for sample_rate.

Returns:

Sample indices, same shape as the input.

Return type:

int | numpy.ndarray[int64]

Example

>>> from audio_samples.utils import time_to_samples
>>> time_to_samples([0.0, 0.5, -0.5], sample_rate=100.0)  # [0, 50, -50]
audio_samples.utils.samples_to_frames(samples, *, hop_length, n_fft=None)

Converts sample indices to frame indices.

floor((samples - n_fft // 2) / hop_length) (the offset only when n_fft is given).

Parameters:
  • samples (int | array_like[int]) – Sample index or indices (may be negative).

  • hop_length (int) – Samples between frames. Required.

  • n_fft (Optional[int]) – Optional frame-length offset.

Returns:

Frame indices, same shape as the input.

Return type:

int | numpy.ndarray[int64]

audio_samples.utils.frames_to_samples(frames, *, hop_length, n_fft=None)

Converts frame indices to sample indices.

frames * hop_length + n_fft // 2 (the offset only when n_fft is given).

Parameters:
  • frames (int | array_like[int]) – Frame index or indices.

  • hop_length (int) – Samples between frames. Required.

  • n_fft (Optional[int]) – Optional frame-length offset.

Returns:

Sample indices, same shape as the input.

Return type:

int | numpy.ndarray[int64]

audio_samples.utils.time_to_frames_floor(times, *, sample_rate=None, hop_length, n_fft=None, sr=None)

Converts times in seconds to the frame containing each time.

samples_to_frames(time_to_samples(t, sample_rate), hop_length, n_fft): truncation to samples, then floor division (negatives kept). Compare time_to_frames, which rounds to the nearest frame.

Parameters:
  • times (float | array_like) – Time(s) in seconds.

  • sample_rate (Optional[float]) – Sampling rate in Hertz. Give this or sr (exactly one).

  • sr (Optional[float]) – Short name for sample_rate.

  • hop_length (int) – Samples between frames. Required.

  • n_fft (Optional[int]) – Optional frame-length offset.

Returns:

Frame indices, same shape as the input.

Return type:

int | numpy.ndarray[int64]

Example

>>> from audio_samples.utils import time_to_frames_floor
>>> time_to_frames_floor([0.0, 0.1, 0.2], sample_rate=22050, hop_length=512)  # [0, 4, 8]
audio_samples.utils.frames_to_time(frames, sample_rate, hop_size, *, n_fft=None)

Converts frame indices to time in seconds.

frames * hop_size / sample_rate, plus (n_fft // 2) / sample_rate when n_fft is given (the frame centre of an uncentred STFT). Negative frames are allowed.

Parameters:
  • frames (int | array_like[int]) – Frame index or indices.

  • sample_rate (float) – Sampling rate in Hertz.

  • hop_size (int) – Samples between frames.

  • n_fft (Optional[int]) – Optional frame-length offset. Default None.

Returns:

Times in seconds, same shape as the input.

Return type:

float | numpy.ndarray[float64]

Example

>>> from audio_samples.utils import frames_to_time
>>> frames_to_time(100, 44100.0, 512)
>>> frames_to_time([0, 1, 2], 22050.0, 512, n_fft=2048)
audio_samples.utils.time_to_frames(time_seconds, sample_rate, hop_size)

Converts times in seconds to the nearest frame index (rounding).

round(t * sample_rate / hop_size), with negative results clamped to 0. time_to_frames_floor returns the frame containing the time instead (floor division, negatives kept, optional n_fft offset).

Parameters:
  • time_seconds (float | array_like) – Time(s) in seconds.

  • sample_rate (float) – Sampling rate in Hertz.

  • hop_size (int) – Samples between frames.

Returns:

Nearest frame indices, same shape as the input.

Return type:

int | numpy.ndarray[int64]

Example

>>> from audio_samples.utils import time_to_frames
>>> time_to_frames(1.0, 44100.0, 512)  # 86
audio_samples.utils.times_like(X, *, sample_rate=None, hop_length, n_fft=None, axis=-1, sr=None)

Time (seconds) of each frame of a feature matrix.

Parameters:
  • X (int | array_like) – Number of frames, or an array whose axis is time.

  • sample_rate (Optional[float]) – Sampling rate in Hertz. Give this or sr (exactly one).

  • sr (Optional[float]) – Short name for sample_rate.

  • hop_length (int) – Samples between frames. Required.

  • n_fft (Optional[int]) – Optional frame-length offset.

  • axis (int) – The time axis of X. Default -1.

Returns:

shape (n_frames,).

Return type:

numpy.ndarray[float64]

audio_samples.utils.samples_like(X, *, hop_length, n_fft=None, axis=-1)

Sample index of each frame of a feature matrix.

Parameters:
  • X (int | array_like) – Number of frames, or an array whose axis is time.

  • hop_length (int) – Samples between frames. Required.

  • n_fft (Optional[int]) – Optional frame-length offset.

  • axis (int) – The time axis of X. Default -1.

Returns:

shape (n_frames,).

Return type:

numpy.ndarray[int64]

mu-law codes

Also available as audio_samples.mu_law_encode / audio_samples.mu_law_decode.

audio_samples.utils.mu_law_encode(x, *, mu=255.0)

Quantise samples to integer μ-law codes.

Companding sign(x) * log1p(mu * |x|) / log1p(mu) followed by binning into floor(1 + mu) levels; for mu=255 the codes are the integers -128..=127. For float-in/float-out companding of a whole signal use AudioSamples.mu_compress.

Parameters:
  • x (float | array_like) – Samples in [-1, 1], any shape.

  • mu (float) – Compression parameter (> 0). Default 255.

Returns:

Codes, same shape as x.

Return type:

int | numpy.ndarray[int64]

Raises:

ValueError – If mu <= 0 or any sample is outside [-1, 1].

Example

>>> from audio_samples import mu_law_encode
>>> mu_law_encode([-1.0, 0.0, 1.0])  # array([-128, 0, 127])
audio_samples.utils.mu_law_decode(codes, *, mu=255.0)

Map integer μ-law codes back to amplitudes.

Not an exact inverse of mu_law_encode (quantisation error up to ~0.043 for mu=255).

Parameters:
  • codes (int | array_like[int]) – μ-law codes, any shape.

  • mu (float) – The mu used for encoding. Default 255.

Returns:

Amplitudes in [-1, 1], same shape.

Return type:

float | numpy.ndarray[float64]

Raises:

ValueError – If mu <= 0 or a code is out of range.

Example

import numpy as np
import audio_samples as aus
from audio_samples import spectral

audio = aus.io.read("speech.wav")
S = audio.melspectrogram(n_mels=64)          # (channels, 64, n_frames)
S_db = spectral.power_to_db(S, ref=np.max)   # per-channel reference
mfcc = audio.mfcc_frames(n_mfcc=13)          # (channels, 13, n_frames)
d_mfcc = spectral.delta(mfcc)                # along the frame axis