% Demonstrate that random (but constant) phase shifts of the
% individual harmonics of a sound wave makes no audible difference.

length = 32768;
period = 256;
harmonics = 200; % Number of harmonics to sum up

% Create a clean sawtooth from a Fourier series

sawtooth = zeros([1, length]);
notsawtooth = zeros([1, length]);

for n = 1:harmonics % Sum up harmonic components
    sawtooth = sawtooth + 0.5/n*sin((0:length-1)/period*n*2*pi);
    notsawtooth = notsawtooth + 0.5/n*sin((0:length-1)/period*n*2*pi + rand*2*pi);
end

plot(0:1023, sawtooth(1:1024), 'r', 0:1023, notsawtooth(1:1024), 'b');

saw = audioplayer(sawtooth, 44100);
notsaw = audioplayer(notsawtooth, 44100);


%%

disp('Playing sawtooth waveform...');
saw.play;

%%

disp('Playing random phase waveform with the same harmonics...');
notsaw.play;

%%
newSaw = (sawtooth + notsawtooth)/2;
playnewsaw = audioplayer(sawtooth, 44100);
playnewsaw.play;