saveSpectrogramPng function
Generates a Mel-frequency spectrogram from a WAV file and saves it as a PNG image.
This function performs the full pipeline:
- Load and resample audio.
- Compute STFT power spectrogram.
- Apply Mel filterbank.
- Convert to dB.
- 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,
);
}