Skip to content

Instantly share code, notes, and snippets.

@svenoaks
Created May 31, 2023 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenoaks/5f911b1204117e763268371e65264b1c to your computer and use it in GitHub Desktop.
Save svenoaks/5f911b1204117e763268371e65264b1c to your computer and use it in GitHub Desktop.
test FormantShifter
int countNaNs(const std::vector<float>& values) {
int count = 0;
for (const float& value : values) {
if (std::isnan(value)) {
count++;
}
}
return count;
}
void testFormantShifter() {
AudioFile<float> audioFile, audioFileReference, audioFileResult;
string filename = "../" + std::string("test1") + ".wav";
string filenameResult = "../" + std::string("formantResult") + ".wav";
audioFile.load(filename);
auto& audioFrames = audioFile.samples;
std::cout << "Total frames: " << audioFile.getNumSamplesPerChannel() << std::endl;
const int channels = audioFrames.size(); // the number of channels is determined by the size of audioFrames
const int samplerate = audioFile.getSampleRate(); // assuming CD quality sound
SMP::FormantShifter shifter(channels, samplerate);
double freqRatio = 0.7; // set to desired value
shifter.setFrequencyRatio(freqRatio);
// The input chunk size
const int inputChunkSize = 4096; // or any other value
// Creating pointers to the channels
std::vector<const float*> channelPointers(channels);
// Process audio frames
int64_t total_frames_written = 0;
for (size_t i = 0; i < audioFrames[0].size(); i += inputChunkSize) {
// Ensuring that the frame size is a multiple of inputChunkSize
if (audioFrames[0].size() - i < inputChunkSize) {
break;
}
// Setting up the input pointers for this chunk
for (int ch = 0; ch < channels; ++ch) {
channelPointers[ch] = &audioFrames[ch][i];
}
auto maxOutputFrames = shifter.maxOutputFrames(inputChunkSize);
// Creating output for this chunk
std::vector<std::vector<float>> outputChunk(channels, std::vector<float>(maxOutputFrames, 0.0f));
// Processing this chunk
int64_t frames_to_write = shifter.process(channelPointers.data(), inputChunkSize, outputChunk);
//int nans = countNaNs(outputChunk[0]);
// Replacing original data with processed data
for (int ch = 0; ch < channels; ++ch) {
std::copy_n(outputChunk[ch].begin(), frames_to_write, audioFrames[ch].data() + total_frames_written);
}
total_frames_written += frames_to_write;
if (true) {
//std::cout << "NaNs: " << nans << std::endl;
//std::cout << "Frames written: " << frames_to_write << std::endl;
//std::cout << "maxOutputFrames: " << maxOutputFrames << std::endl;
}
}
//std::cout << "Total frames written: " << total_frames_written << std::endl;
audioFile.save(filenameResult);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment