Skip to main content

Function Signature

Pads or trims an audio array to a fixed length, as expected by the Whisper encoder. This ensures all audio inputs have consistent dimensions for batch processing.

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)

If array.shape[axis] > length, the array is trimmed:
  • For PyTorch tensors: Uses index_select to select the first length elements along the specified axis.
  • For NumPy arrays: Uses take with indices=range(length) along the specified axis.

When Array is Too Short (Padding)

If array.shape[axis] < length, the array is zero-padded on the right:
  • For PyTorch tensors: Uses F.pad to add zeros.
  • For NumPy arrays: Uses np.pad with zero padding.

When Array is Exact Length

If array.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.