Array Forms and Options

audio_samples.forms holds array forms of methods, for options that an AudioSamples makes unnecessary or that need another input.

Array forms and extra options of common operations.

These functions take and return NumPy arrays, and cover options that the methods of AudioSamples leave out because an AudioSamples makes them unnecessary: several signals of different lengths, a reading window, resampling with an energy scale, dense event masks, and framing along any axis. They build on the operations of this package.

audio_samples.forms.beat_track(*, y=None, sr=22050, onset_envelope=None, hop_length=512, sparse=True, **kwargs)[source]

Tempo and beat frames, as indices or as a boolean mask over the frames.

Parameters:
  • y (NDArray[Any] | None) – Samples, when onset_envelope is not given.

  • sr (float) – Sample rate in Hz.

  • onset_envelope (NDArray[Any] | None) – Onset strength per frame.

  • hop_length (int) – Samples between frames.

  • sparse (bool) – Return indices; otherwise a boolean mask.

  • **kwargs (Any) – Passed to rhythm.beat_track.

Returns:

The tempo, and the indices or a mask of one element per frame.

Return type:

tuple[Any, NDArray[Any]]

audio_samples.forms.chroma_cens(*, C, fmin=None, n_chroma=12, bins_per_octave=36, window=None, norm=2, win_len_smooth=41, smoothing_window='hann')[source]

Chroma energy normalised statistics of a constant-Q magnitude spectrogram.

Parameters:
  • C (NDArray[Any]) – Magnitudes, (..., n_bins, frames).

  • fmin (float | None) – As chroma_cqt().

  • n_chroma (int) – As chroma_cqt().

  • bins_per_octave (int) – As chroma_cqt().

  • window (NDArray[Any] | None) – As chroma_cqt().

  • norm (float | None) – Final normalisation of each frame.

  • win_len_smooth (int | None) – Length of the time smoothing; None for none.

  • smoothing_window (Any) – Window of the time smoothing.

Returns:

The features.

Return type:

NDArray[Any]

audio_samples.forms.chroma_cqt(*, C, fmin=None, norm=inf, threshold=0.0, n_chroma=12, window=None, bins_per_octave=36)[source]

Chromagram of a constant-Q magnitude spectrogram.

Parameters:
  • C (NDArray[Any]) – Magnitudes, (..., n_bins, frames).

  • fmin (float | None) – Frequency of the first bin in Hz. None means C1.

  • norm (float | None) – Normalisation of each frame.

  • threshold (float | None) – Values below this become zero.

  • n_chroma (int) – Chroma bins.

  • window (NDArray[Any] | None) – Smoothing weights for each chroma row across constant-Q bins.

  • bins_per_octave (int) – Constant-Q bins per octave.

Returns:

The chromagram, in the precision of C.

Return type:

NDArray[Any]

audio_samples.forms.chroma_vqt(*, V, fmin=None, norm=inf, threshold=0.0, bins_per_octave=12)[source]

Chromagram with one bin per variable-Q bin of an octave.

Parameters:
  • V (NDArray[Any]) – Magnitudes, (..., n_bins, frames).

  • fmin (float | None) – Frequency of the first bin in Hz. None means C1.

  • norm (float | None) – Normalisation of each frame.

  • threshold (float | None) – Values below this become zero.

  • bins_per_octave (int) – Variable-Q bins per octave, and chroma bins.

Returns:

The chromagram.

Return type:

NDArray[Any]

audio_samples.forms.frame(x, *, frame_length, hop_length, axis=-1, writeable=False, subok=False)[source]

Slices an array into overlapping frames along any axis.

Parameters:
  • x (NDArray[Any]) – The array.

  • frame_length (int) – Samples per frame.

  • hop_length (int) – Samples between frames.

  • axis (int) – The axis to frame. With a negative axis the frames take the last position; with a positive axis they take its place.

  • writeable (bool) – The result may be written to, which writes through to x.

  • subok (bool) – Keep an array subclass.

Returns:

A view with one more dimension.

Raises:

ValueError – The axis is shorter than one frame, or a length is not positive.

Return type:

NDArray[Any]

audio_samples.forms.get_duration(*, y=None, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, path=None)[source]

The duration in seconds of samples, of a spectrogram, or of a file.

Parameters:
  • y (NDArray[Any] | None) – Samples with time on the last axis.

  • sr (float) – Sample rate in Hz of y or S.

  • S (NDArray[Any] | None) – A spectrogram with frames on the last axis.

  • n_fft (int) – FFT size of S.

  • hop_length (int) – Samples between the frames of S.

  • center (bool) – The frames of S are centred.

  • path (str | PathLike[str] | None) – A file, whose header gives the duration.

Returns:

The duration.

Raises:

ValueError – None of y, S and path is given.

Return type:

float

audio_samples.forms.istft(stft_matrix, *, hop_length=None, win_length=None, n_fft=None, window='hann', center=True, length=None, out=None)[source]

Inverse short-time Fourier transform, optionally into a given buffer.

Parameters:
  • stft_matrix (NDArray[Any]) – The complex spectrogram.

  • hop_length (int | None) – As spectral.istft.

  • win_length (int | None) – As spectral.istft.

  • n_fft (int | None) – As spectral.istft.

  • window (Any) – As spectral.istft.

  • center (bool) – As spectral.istft.

  • length (int | None) – As spectral.istft.

  • out (NDArray[Any] | None) – Array to write the result to, of at least the result’s length. The samples that are written are returned as a view of it.

Returns:

The samples.

Return type:

NDArray[Any]

audio_samples.forms.onset_detect(*, y=None, sr=22050, onset_envelope=None, hop_length=512, sparse=True, **kwargs)[source]

Onset frames, as indices or as a boolean mask over the frames.

Parameters:
  • y (NDArray[Any] | None) – Samples, when onset_envelope is not given.

  • sr (float) – Sample rate in Hz.

  • onset_envelope (NDArray[Any] | None) – Onset strength per frame.

  • hop_length (int) – Samples between frames.

  • sparse (bool) – Return indices; otherwise a boolean mask.

  • **kwargs (Any) – Passed to rhythm.onset_detect.

Returns:

Indices, or a mask of one element per frame.

Return type:

NDArray[Any]

audio_samples.forms.onset_strength(*, y=None, sr=22050, S=None, lag=1, max_size=1, ref=None, detrend=False, center=True, feature=None, n_fft=2048, hop_length=512, **kwargs)[source]

Onset strength with any time-frequency feature.

Parameters:
  • y (NDArray[Any] | None) – Samples, if S is None.

  • sr (float) – Rate of the samples in Hz.

  • S (NDArray[Any] | None) – Log-power spectrogram, (..., n_bins, frames).

  • lag (int) – Frames between the compared spectra.

  • max_size (int) – Size of the frequency maximum filter on the reference.

  • ref (NDArray[Any] | None) – Reference spectrogram, of the shape of S.

  • detrend (bool) – Remove the slowly varying component.

  • center (bool) – Align the envelope with centred frames.

  • feature (Any) – Called as feature(y=y, sr=sr, n_fft=n_fft, hop_length=hop_length, **kwargs); its magnitude in decibels, limited to 80 dB below the peak, is the spectrogram. None uses the mel spectrogram.

  • n_fft (int) – Passed to feature, and used by center.

  • hop_length (int) – Passed to feature, and used by center.

  • **kwargs (Any) – Passed to feature.

Returns:

The envelope of each channel, with one row removed for a single channel.

Return type:

NDArray[Any]

audio_samples.forms.pitch_shift(y, *, sr, n_steps, bins_per_octave=12, scale=False, **kwargs)[source]

Shifts the pitch of an array without changing its length.

Parameters:
  • y (NDArray[Any]) – Samples with time on the last axis, 1-D or 2-D.

  • sr (int) – Its rate in Hz.

  • n_steps (float) – Fractional steps to shift by.

  • bins_per_octave (int) – Steps per octave.

  • scale (bool) – Divide by the square root of the resampling ratio, as resample().

  • **kwargs (Any) – Passed to AudioSamples.pitch_shift.

Returns:

The shifted array.

Return type:

NDArray[Any]

audio_samples.forms.read_segment(path, *, offset=0.0, duration=None, **kwargs)[source]

Reads part of an audio file.

Parameters:
  • path (str | PathLike[str]) – The file.

  • offset (float) – Start in seconds.

  • duration (float | None) – Length in seconds. Default: to the end.

  • **kwargs (Any) – as_type is the sample type to read as; the file’s by default.

Returns:

AudioSamples of the part, with the file’s rate and channels. Only that part is read.

Raises:

ValueError – A negative offset or duration.

Return type:

Any

audio_samples.forms.reassigned_spectrogram(y, *, sr=22050, S=None, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, reassign_frequencies=True, reassign_times=True, ref_power=1e-06, fill_nan=False, clip=True, pad_mode='constant')[source]

Reassigned spectrogram with a given spectrogram for the main window.

Without S this is AudioSamples.reassigned_spectrogram. With S, its values replace those of the STFT with the analysis window, in the corrections and in the magnitudes; the two other STFTs still come from y.

Parameters:
  • y (NDArray[Any]) – Samples with time on the last axis.

  • sr (int) – Rate of the samples in Hz.

  • S (NDArray[Any] | None) – Complex spectrogram of the analysis window.

  • n_fft (int) – As for the STFT.

  • hop_length (int | None) – As for the STFT.

  • win_length (int | None) – As for the STFT.

  • window (Any) – As for the STFT.

  • center (bool) – As for the STFT.

  • pad_mode (Any) – As for the STFT.

  • reassign_frequencies (bool) – Correct the frequencies.

  • reassign_times (bool) – Correct the times.

  • ref_power (float) – Bins below this power, relative to a callable’s result if it is one, have no correction.

  • fill_nan (bool) – Fill uncorrected bins with the bin centres; otherwise NaN.

  • clip (bool) – Keep corrections within the frequency and time range of the spectrogram.

Returns:

(frequencies, times, magnitudes).

Return type:

tuple[NDArray[Any], NDArray[Any], NDArray[Any]]

audio_samples.forms.resample(y, *, orig_sr, target_sr, res_type='soxr_hq', fix=True, scale=False)[source]

Resamples an array.

Parameters:
  • y (NDArray[Any]) – Samples with time on the last axis, 1-D or 2-D.

  • orig_sr (int) – Its rate in Hz.

  • target_sr (int) – The new rate in Hz.

  • res_type (str) – "soxr_hq", "soxr_mq", "soxr_lq", "high", "medium" or "fast".

  • fix (bool) – The length is ceil(n * target_sr / orig_sr). The resampler always gives this length, so this has no other value.

  • scale (bool) – Divide by the square root of the ratio, which keeps total energy (as one multiplication by its reciprocal: within one rounding of the quotient).

Returns:

The resampled array, of y’s dtype.

Return type:

NDArray[Any]

audio_samples.forms.salience(S, *, freqs, harmonics, weights=None, aggregate=None, filter_peaks=True, fill_value=nan, kind='linear', axis=-2)[source]

Harmonic salience with any interpolant along any frequency axis.

Parameters:
  • S (NDArray[Any]) – Energy.

  • freqs (NDArray[Any]) – Frequencies of the frequency axis, 1-D.

  • harmonics (Any) – Harmonic multipliers.

  • weights (Any) – Weight of each harmonic in the default aggregate. None weighs them equally.

  • aggregate (Any) – Called as aggregate(values, axis=...). None uses the weighted average.

  • filter_peaks (bool) – Keep only the local maxima of S along the frequency axis.

  • fill_value (float) – Value everywhere else.

  • kind (Any) – Interpolation kind.

  • axis (int) – The frequency axis.

Returns:

The salience, of the shape of S.

Return type:

NDArray[Any]

audio_samples.forms.stft(y, *, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant', sr=22050, dtype=None, out=None)[source]

Short-time Fourier transform of an array, optionally into a given buffer.

Parameters:
  • y (NDArray[Any]) – Samples with time on the last axis, 1-D or 2-D.

  • n_fft (int) – As AudioSamples.stft_matrix.

  • hop_length (int | None) – As AudioSamples.stft_matrix.

  • win_length (int | None) – As AudioSamples.stft_matrix.

  • window (Any) – As AudioSamples.stft_matrix.

  • center (bool) – As AudioSamples.stft_matrix.

  • pad_mode (Any) – As AudioSamples.stft_matrix.

  • sr (int) – Rate of the samples; the transform does not depend on it.

  • dtype (Any) – complex64 or complex128, by converting the samples first. None follows the samples.

  • out (NDArray[Any] | None) – Array to write the result to. It may be longer in time than the result; the frames that are written are returned as a view of it.

Returns:

The complex spectrogram.

Return type:

NDArray[Any]

audio_samples.forms.stream_blocks(path, *, block_length, frame_length, hop_length, sr=None, mono=False, offset=0.0, duration=None, fill_value=None, res_type='soxr_hq')[source]

Iterates over blocks of a file, each covering block_length frames.

Parameters:
  • path (str | PathLike[str]) – The file.

  • block_length (int) – Frames per block.

  • frame_length (int) – Samples per frame.

  • hop_length (int) – Samples between frames.

  • sr (int | None) – Resample to this rate. Default: keep the file’s rate.

  • mono (bool) – Mix to one channel.

  • offset (float) – Start in seconds.

  • duration (float | None) – Length in seconds. Default: to the end.

  • fill_value (float | None) – Pad the last block to full length with this value; otherwise a short last block is returned as it is.

  • res_type (str) – Resampler quality when sr is given.

Yields:

Arrays with time on the last axis.

Raises:

ValueError – A parameter is not positive.

Return type:

Iterator[NDArray[Any]]

audio_samples.forms.tempogram_ratio(*, tg, bpm, sr=22050, hop_length=512, freqs=None, factors=None, kind='linear', fill_value=0.0)[source]

Tempogram at multiples of the tempo, with given tempo frequencies.

Parameters:
  • tg (NDArray[Any]) – Tempogram, (..., n_lags, frames).

  • bpm (NDArray[Any]) – Tempo per frame, in beats per minute.

  • sr (float) – Used when freqs is None.

  • hop_length (int) – Used when freqs is None.

  • freqs (NDArray[Any] | None) – The tempo of each row of tg.

  • factors (NDArray[Any] | None) – Multiples of the tempo. None means the metric multiples of Prockup et al. (2015).

  • kind (Any) – Interpolation kind.

  • fill_value (float) – Value outside the tempo range.

Returns:

tg interpolated at factors * bpm, (..., n_factors, frames).

Return type:

NDArray[Any]

audio_samples.forms.to_mono(*signals, pad=True, norm=True, out=None)[source]

Mixes the channels of one or more signals to one channel.

Parameters:
  • *signals (NDArray[Any]) – Arrays with time on the last axis.

  • pad (bool) – Pad shorter signals to the longest; otherwise trim to the shortest.

  • norm (bool) – Average the channels; otherwise sum them.

  • out (NDArray[Any] | None) – Array to write the result to.

Returns:

The mixed signal.

Raises:

ValueError – No signals, or a wrong out shape.

Return type:

NDArray[Any]

audio_samples.forms.to_multi(*signals, downmix=True, pad=True, norm=True, out=None)[source]

Combines signals into one array with a leading channel axis.

Parameters:
  • *signals (NDArray[Any]) – Arrays with time on the last axis.

  • downmix (bool) – Give each signal one channel of the result; otherwise mix signals of one channel layout, channel by channel.

  • pad (bool) – Pad to the longest signal; otherwise trim to the shortest.

  • norm (bool) – With downmix, average each signal’s channels; otherwise divide the mix by the number of signals.

  • out (NDArray[Any] | None) – Array to write the result to.

Returns:

The combined array.

Raises:

ValueError – No signals, a non-finite signal, or different layouts with downmix=False.

Return type:

NDArray[Any]

audio_samples.forms.to_stereo(*, left, right, downmix=True, pad=True, norm=True, out=None)[source]

Combines signals into two channels.

Parameters:
  • left (NDArray[Any] | None) – The left signal; None leaves it silent.

  • right (NDArray[Any] | None) – The right signal; None leaves it silent.

  • downmix (bool) – Mix each input to one channel first. Otherwise a stereo input is summed with the other side.

  • pad (bool) – Pad to the longer signal; otherwise trim to the shorter.

  • norm (bool) – With downmix, average each input’s channels; otherwise halve the sum of two inputs.

  • out (NDArray[Any] | None) – Array to write the (2, n) result to.

Returns:

A (2, n) array.

Raises:

ValueError – No inputs, or an input of a shape this cannot combine.

Return type:

NDArray[Any]