liamappelbe / fftea

A simple and efficient FFT implementation for Dart
Apache License 2.0
63 stars 1 forks source link

Audio resampling util? #38

Closed liamappelbe closed 1 year ago

liamappelbe commented 1 year ago

Changing the sample rate of an audio signal is another super common use case of FFT that would make for a good util, like the convolution util.

liamappelbe commented 1 year ago

The algorithm is really simple: FFT(input length) -> truncate or zero pad to the new length -> inverse FFT(new length) You also need to adjust the output volume based on the resampling ratio.

final ratio = outSampleRate.toDouble() / inSampleRate;
final infft = FFT(input.length);
final outfft = FFT((input.length* ratio).round());
final infreq = infft.realFft(input).discardConjugates();
final outfreq = Float64x2List(newLength).discardConjugates();
final copyLength = min(infreq.length, outfreq.length);
for (int i = 0; i < copyLength; ++i) {
  outfreq[i] = infreq[i];
}
final out = outfft.realInverseFft(outfreq.createConjugates(newLength));
for (int i = 0; i < out.length; ++i) {
  out[i] *= ratio;
}