4. Crossfading

Up next are the slightly non-trivial bits of this program. Overall read position is kept track of. While this position is in the fade region, the file is read from the beginning and simultaneously. This requires an extra buffer, and a way to jump back and forth between positions in the files.

If it happens that the read position is still in the fade region, the file will seek to the outfile end position plus the read position as an offset, and fill up a buffer that is COUNT samples long.

<<read_end>>=
drwav_seek_to_sample(&infile, endpos + pos);
count = drwav_read_f32(&infile, BUFSIZE, endbuf);
<<snap_it_back>>

This buffer will then be scaled and summed into the output buffer.

Scaling is done using a normalized alpha value, which is the current sample position, divided by the fade time. The end block gets multiplied by alpha. Beginning block is one minus alpha.

<<scale_and_sum>>=
float beg, end;
float a;
beg = buf[n];
end = endbuf[n];
a = (float)pos / fade;
buf[n] = (1 - a) * end + a * beg;

With the end read done, the file can jump back to the previous position and go COUNT samples further, in order to get ready for the next read.

<<snap_it_back>>=
drwav_seek_to_sample(&infile, pos + count);



prev | home | next