librosa.util.align_samples#
- librosa.util.align_samples(n_samples, *, orig_sr, target_sr=None, error=False)[source]#
Calculate the integer-aligned sample count when converting between sampling rates.
This function determines whether a duration spanning n_samples at sampling rate orig_sr corresponds to an exact integer number of samples at target_sr (within numerical precision tolerances).
This is primarily useful in streaming audio workflows to ensure that block advances or buffer sizes align exactly between the input capture rate and downstream analysis rate without cumulative fractional sample drift.
- Parameters:
- n_samplesint > 0
Number of samples at rate orig_sr.
- orig_srfloat > 0
Sampling rate corresponding to n_samples.
- target_srfloat > 0, optional
Target sampling rate. If None, defaults to orig_sr.
- errorbool, default=False
If True, raises ParameterError when the sample count does not align to an integer. If False, returns None.
- Returns:
- aligned_samplesint or None
The corresponding sample count at target_sr. If the combination results in a non-integer sample count and error=False, returns None.
- Raises:
- ParameterValueError
If n_samples is not a positive integer. If orig_sr or target_sr is not a positive number. If error=True and the sample count does not evaluate to an integer at target_sr.
See also
Examples
Check if a 512-sample hop at 22,050 Hz aligns at 44,100 Hz:
>>> librosa.util.align_samples(512, orig_sr=22050, target_sr=44100) 1024
Check compatibility between 48,000 Hz and 22,050 Hz:
>>> librosa.util.align_samples(512, orig_sr=48000, target_sr=22050) None
Raise an exception on non-integer alignment:
>>> librosa.util.align_samples(512, orig_sr=48000, target_sr=22050, error=True) Traceback (most recent call last): ... librosa.util.exceptions.ParameterValueError: Sample count of 512 at 48000...