Clicks when changing BufRd buffers [Solved]

Hi all, I’m using BufRd to index into buffers which I replace constantly with modified versions of themselves. While a synth is running these buffers are being indexed by a looping phasor ~t, so when a buffer is replaced by another one (of the same length) the indexing continues where the previous one left off. An example:

SynthDef(\fm, {
        // these are all buffers that get updated
	arg amp, freq, ratio, index, pan;

	var freq_ = BufRd.kr(1, freq, In.ar(~t) * BufFrames.kr(freq));
	var ratio_ = BufRd.kr(1, ratio, In.ar(~t) * BufFrames.kr(ratio));
	var index_ = BufRd.kr(1, index, In.ar(~t) * BufFrames.kr(index));
	var amp_ = BufRd.kr(1, amp, In.ar(~t) * BufFrames.kr(amp));
	var pan_ = BufRd.kr(1, pan, In.ar(~t) * BufFrames.kr(pan));

	var mod = SinOsc.ar(freq_*ratio_)*index_;
	var sig = SinOsc.ar(freq_ + mod) * amp_;

	Out.ar(~reverbOut, Pan2.ar(sig, pan_));
})

The buffer files themselves are being overwritten, and when the new one is ready this gets called to free the old one and load the new:

bufferDict[buffName].free;
bufferDict.add(buffName -> Buffer.read(server, filePath, action: {|b|
    synthDict[synthName].set(synthParam, b)}));

I understand that there will be clicks if there are discontinuities between the values of the previous and the new buffers, and using Lag doesn’t help as it also smooths changes in the actual indexed values. The problem is that I keep getting audible pops and clicks, even when a buffer is replaced by an identical one (and so there is no discontinuity with the previous value). As I am live coding these buffers and replacing them all the time, this gets pretty annoying.

Why are there discontinuities even when a buffer with a constant value is replaced by an identical one? Is it that I’m freeing the old one before the new is loaded?

As soon as I finished writing this it dawned on me that it probably was the freeing-before-loading thing, I tested it and I was right!

var oldBuff = bufferDict[buffName];
bufferDict.add(buffName -> Buffer.read(server, filePath, action: { |b|
	synthDict[synthName].set(synthParam, b);
	oldBuff.free;
}));

Solved my own problem before anyone even read this post, there must be some kind of badge for that!

As a bonus question (and so this thread doesn’t die in vain): How could I use Lag to smooth changes only when the buffer is changed and not in between changes?

+1 :slight_smile:

IMO the clean solution for this is crossfading between playing buffers. E.g. you could crossfade between two channels with SelectX and exchange the silently-playing buffer on occasion, then fade back.
Besides SelectX you could use DX ugens from miSCellaneous_lib quark. In contrast to SelectX you can crossfade arbitrarily between many signals resp. playing buffers, with SelectX you must slide over the neighbours if the array is larger.