Function Signature
Parameters
Union[np.ndarray, torch.Tensor]
required
The input audio array to pad or trim. Can be either a NumPy array or PyTorch tensor.
int
default:"480000"
The target length for the array. Defaults to
N_SAMPLES (480000), which represents 30 seconds of audio at 16 kHz sample rate.int
default:"-1"
The axis along which to pad or trim. Defaults to
-1 (last axis). This is a keyword-only argument.Returns
Union[np.ndarray, torch.Tensor]
The padded or trimmed array with shape matching the input type. If a NumPy array was provided, returns NumPy array. If a PyTorch tensor was provided, returns PyTorch tensor.
Example
Behavior
When Array is Too Long (Trimming)
Ifarray.shape[axis] > length, the array is trimmed:
- For PyTorch tensors: Uses
index_selectto select the firstlengthelements along the specified axis. - For NumPy arrays: Uses
takewithindices=range(length)along the specified axis.
When Array is Too Short (Padding)
Ifarray.shape[axis] < length, the array is zero-padded on the right:
- For PyTorch tensors: Uses
F.padto add zeros. - For NumPy arrays: Uses
np.padwith zero padding.
When Array is Exact Length
Ifarray.shape[axis] == length, the array is returned as-is.
Audio Constants
Multi-Dimensional Arrays
The function works on arrays of any dimensionality:Integration with Preprocessing Pipeline
Performance Considerations
- The function preserves the input type (NumPy or PyTorch) and device (for tensors).
- For PyTorch tensors on GPU, padding/trimming operations remain on the same device.
- Zero-padding is memory-efficient and does not require data copying for the original samples.