% https://uk.mathworks.com/matlabcentral/answers/56761-how-can-overlap-add-technique-be-done
% largely modified

%%
 chdir 'C:\Users\rampo\Dropbox\_________DSP_23\S03.4a_AudacityEtc';
% chdir 'C:\Users\3362\Dropbox\_________DSP_23\S03.4a_AudacityEtc';

clear all;
 load handel; x=y'; clear y; x=x(1:20550);
% x = sin(.085*pi*(1:15000))*.8; % x=x';
% y = audioread('dsp01.wav'); x=y(1:round(44100/8192):end)'; clear y;

Fs = 8192;
N = length(x);

M_ms = 20;   %  frame duration (milliseconds)
M = round(Fs*M_ms/1000)   %  frame duration (samples)
alpha = 2^(6/12); %  2^(2/12) = 2 semitones up
%  alpha = 1 / alpha;   %  or down
Hs = M/2;  % M/2 or M/4   %  synthesis hopsize
Ha = round(Hs/alpha);     %  analysis hopsize

x = [x zeros(1,M+Ha+1)]; % otherwise indices k exceed length of x

  wind = ones(1,M);
  wind = hann(M)';

y = zeros(1,ceil(N/alpha)); % zeros(1,N);

xm = x(1:M) .* wind;
for k = 1:floor(N/Ha)-1; 
    xm = [xm; x(k*Ha+1:k*Ha+M) .* wind];
end
 
y = [x(1:M)  zeros(1,Hs)];
for k = 1:floor(N/Ha)-1;
    xms = [zeros(1,k*Hs)  xm(k,:)];
    y = [y+xms   zeros(1,Hs)];
end

subplot(411), plot(x(1:N)), axis tight;
subplot(412), plot(y(1:floor(N*alpha))), axis tight
subplot(413), plot(20*log10(abs(fft(x(1:N))))), axis tight;
subplot(414), plot(20*log10(abs(fft(y(1:floor(N*alpha)))))), axis tight

 return
%%
  sound(x,Fs); pause(N/Fs+2);        % orig
   sound(y,Fs); pause(N*alpha/Fs+2);  % change tempo (duration changes, pitch stable)
   sound(y,Fs*alpha); pause(N/Fs+2);  % change pitch (duration stable)
  sound(x,Fs*alpha); pause(N*alpha/Fs+2);  % change speed (duration and pitch change)

return
    
 