slidingWindow function

Iterable<(int, Float32List)> slidingWindow(
  1. Float32List waveform,
  2. int windowSize,
  3. int stepSize
)

Generates sliding windows over the audio data.

Returns an iterable of tuples containing:

  • Window size in samples
  • Window data as Float32List

The last window may be padded if it's incomplete.

Implementation

Iterable<(int, Float32List)> slidingWindow(
  Float32List waveform,
  int windowSize,
  int stepSize,
) sync* {
  int start = 0;
  final numSamples = waveform.length;

  // Process full windows
  while (start <= numSamples - windowSize) {
    yield (
      windowSize,
      Float32List.sublistView(waveform, start, start + windowSize),
    );
    start += stepSize;
  }

  // Handle last incomplete window if needed
  if (numSamples < windowSize || (numSamples - windowSize) % stepSize > 0) {
    final lastWindow = Float32List.sublistView(waveform, start);
    final lastWindowSize = lastWindow.length;

    if (lastWindowSize < windowSize) {
      // Create padded window
      final paddedWindow = Float32List(windowSize);
      paddedWindow.setAll(0, lastWindow);
      // Remaining elements are already 0 by default
      yield (lastWindowSize, paddedWindow);
    } else {
      yield (lastWindowSize, lastWindow);
    }
  }
}