% acomp.m 
% compress an audio sound using global Fourier transform 
% parameters 
% desired compression  (i.e % of Fourier coefficients to be kept)

p = 10
% load sound 
% y is the sound vector y 
% and Fs is the sample rate
load('splat')

ly = length(y);
secs = ly/Fs;
y = y/max(abs(y));

% get FFT of y
z=fft(y);
maz =  max(abs(z));

% plot y 
figure(1)  
clf
plot((0:(ly-1))/Fs,y,'.r'); 
axis([0,secs,-1,1]);
title('original signal')


% plot absolute value of fft
figure(2)
plot(0:(length(z)-1),abs(z),'.r');
axis([0,ly,-0.1*maz,maz]);     
title('original |fft|');
drawnow
disp('Press a key for compressed signals')
pause


% clip out small stuff
saz = sort(abs(z));
cutlev = saz(round((1-p/100)*length(saz))); 
J = find(abs(z) < cutlev);
cz = z;
cz(J) = zeros(size(J));
cy = real(ifft(cz));


% plot compressed fft
figure(3)
clf
plot(0:(length(z)-1),abs(cz),'.r');
hold on;
plot(0:(length(z)-1),cutlev*ones(size(cz)),'-y'); 
axis([0,ly,-0.1*maz,maz]);    
title('compressed |fft|');

% plot compressed signal
figure(4)  
plot((0:(ly-1))/Fs,cy,'.r');
axis([0,secs,-1,1]);
title('compressed signal');


% listen to the sounds
disp(' press a key for original sound'); 
pause
sound(y)
disp(' press a key for reconstructed sound'); 
pause
sound(cy)

% Compute compression
PercentRetainedCoefficients = 100*(ly-length(J))/ly

% compute logarithm of cutoff level
  logcutlev = -log10(cutlev/maz); 