%% Reconstruct Audio Signal from STFT Magnitude
% Load an audio signal that contains two decreasing chirps and a wideband splatter sound. The signal is sampled at 8192 Hz. Plot the STFT of the signal. Divide the waveform into 128-sample segments and window the segments using a Hamming window. Specify 64 samples of overlap between adjoining segments and 1024 FFT points.

load splat
ty = (0:length(y)-1)/Fs;

% To hear, type sound(y,Fs)

wind = hamming(128);
olen = 64;
nfft = 1024;

stft(y,Fs,'Window',wind,'OverlapLength',olen,'FFTLength',nfft)

%
% Compute the magnitude and phase of the STFT.

s = stft(y,Fs,'Window',wind,'OverlapLength',olen,'FFTLength',nfft);

smag = abs(s);
sphs = angle(s);

%
% Reconstruct the signal based on the magnitude of the STFT. Use the same parameters that you used to compute the STFT. By default, stftmag2sig initializes the phases to zero and uses 100 optimization iterations.

[x,tx,info] = stftmag2sig(smag,nfft,Fs,'Window',wind,'OverlapLength',olen);

% To hear, type sound(x,Fs)

% Plot the original and reconstructed signals. For better comparison, offset the reconstructed signal up and to the right.

plot(ty,y,tx+500/Fs,x+1)
legend('Original','Reconstructed','Location','best')

% Output the relative improvement toward convergence between the last two iterations.

impr = info.Inconsistency

%
% Improve the reconstruction by doubling the number of optimization iterations and setting the initial phases to the actual phases from the STFT. Plot the original and reconstructed signals. For better comparison, plot the negative of the reconstructed signal and offset it up and to the right.

[x,tx,info] = stftmag2sig(smag,nfft,Fs,'Window',wind,'OverlapLength',olen, ...
    'MaxIterations',200,'InitialPhase',sphs);

% To hear, type sound(x,Fs)

plot(ty,y,tx+500/Fs,-x+1)
legend('Original','Reconstructed','Location','best')

% Output the relative improvement toward convergence between the last two iterations.

impr = info.Inconsistency

% Copyright 2020 The MathWorks, Inc.