saveSpectrogramPng function

Future<void> saveSpectrogramPng(
  1. String wavPath,
  2. String pngPath, {
  3. int sampleRate = 22050,
  4. int nFft = 2048,
  5. int? hopLength,
  6. int nMels = 128,
  7. double fMin = 0.0,
  8. double? fMax,
  9. double topDb = 80.0,
  10. String title = 'Mel-frequency spectrogram',
  11. int plotWidth = 1000,
  12. int plotHeight = 400,
  13. bool useNearest = true,
})

Generates a Mel-frequency spectrogram from a WAV file and saves it as a PNG image.

This function performs the full pipeline:

  1. Load and resample audio.
  2. Compute STFT power spectrogram.
  3. Apply Mel filterbank.
  4. Convert to dB.
  5. Render to an image using the Magma colormap and save to disk.

Implementation

Future<void> saveSpectrogramPng(
  String wavPath,
  String pngPath, {
  int sampleRate = 22050,
  int nFft       = 2048,
  int? hopLength,
  int nMels      = 128,
  double fMin    = 0.0,
  double? fMax,
  double topDb   = 80.0,
  String title   = 'Mel-frequency spectrogram',
  int plotWidth  = 1000,
  int plotHeight = 400,
  bool useNearest = true,
}) async {
  final hop     = hopLength ?? nFft ~/ 4;

  final audio   = await loadAudio(wavPath, sampleRate);

  final power   = calculateSpectrogram(audio.samples, fftSize: nFft, hopSize: hop);

  final fbank   = createMelFilterbank(
    sampleRate: sampleRate, nFft: nFft, nMels: nMels, fMin: fMin, fMax: fMax,
  );

  final melSpec = applyMelFilterbank(power, fbank);

  final melDb   = powerToDb(melSpec, topDb: topDb);

  await saveSpectrogramImage(
    melDb, pngPath,
    sampleRate: sampleRate,
    hopLength: hop,
    fMin:       fMin,
    fMax:       fMax ?? sampleRate / 2.0,
    topDb:      topDb,
    title:      title,
    plotWidth:  plotWidth,
    plotHeight: plotHeight,
    useNearest: useNearest,
  );
}