NAudio icon indicating copy to clipboard operation
NAudio copied to clipboard

OffsetSampleProvider breaks when Delay ends with samplesRead == count

Open origfla opened this issue 3 years ago • 0 comments

I am using an OffsetSampleProvider to simply add silence at the start and end of my tracks as follows:

var offsetSampleProvider = new OffsetSampleProvider(trackSampleProvider);
offsetSampleProvider.DelayBy = track.StartTime;
offsetSampleProvider.LeadOut = track.EndGap;

What I've discovered is if the DelayBy is set to a specific value such that, in this section of the read code:

if (phase == 1) // delay
{
    int delaySamples = Math.Min(count, DelayBySamples - phasePos);
    for (int n = 0; n < delaySamples; n++)
    {
        buffer[offset + n] = 0;
    }
    phasePos += delaySamples;
    samplesRead += delaySamples;
    if (phasePos >= DelayBySamples)
    {
        phase++;
        phasePos = 0;
    }
}

You get the following situation (one exact full read occurs directly as we reach the end of phase 1):

  • samplesRead == count
  • phasePos >= DelayBySamples

You progress to the next phase and, in my case, it progresses to phase 3 in the same read call and, in phase 3, where the read line of code throws an error:

int read = sourceProvider.Read(buffer, offset + samplesRead, samplesRequired);

I was able to correct this by forcing this call to read to not enter into the if statement in phase 1 as follows:

if (phasePos >= DelayBySamples && samplesRead < count)

I'm not sure if this is just a hack or a feasible solution, but it has worked for me.

origfla avatar Jan 19 '22 20:01 origfla