Hi everyone,
I’m implementing a custom rewrite of the Synthesiser class and one of the features I wanted for my application is the ability for the user to dynamically update the number of voices on the fly. Obviously, continuity of sound while doing this isn’t always possible or a priority, but I did come up with a little function so that if you’re removing voices, it first removes voices that are currently silent. I thought this might be a handy feature to include in the Synthesiser class, or possibly this might be useful to someone else out there ¯_(ツ)_/¯
Here’s the top-level function in my plugin processor:
void AudioProcessor::updateNumVoices(const int newNumVoices)
{
if(const int currentVoices = synth.getNumVoices(); currentVoices != newNumVoices)
{
if(newNumVoices > currentVoices)
{
const int voicesToAdd = newNumVoices - currentVoices;
for(int i = 0; i < voicesToAdd; ++i)
synth.addVoice(new SynthesiserVoice);
}
else
{
synth.removeNumVoices(currentVoices - newNumVoices); // this is a custom function I added to the synth class, see below...
}
}
};
and here’s the removeNumVoices() function, which goes inside the synthesiser class:
void Synthesiser::removeNumVoices(const int voicesToRemove)
{
const ScopedLock sl (lock);
int voicesRemoved = 0;
while(voicesRemoved < voicesToRemove)
{
int indexToRemove = -1;
for(auto* voice : voices)
{
if(! voice->isVoiceActive())
{
indexToRemove = voices.indexOf(voice);
break;
}
}
if(indexToRemove > -1)
voices.remove(indexToRemove);
else
voices.remove(0);
++voicesRemoved;
}
};