% Ronan O'Malley
% September 16th 2005
% clipper.m
% M Script that clips amplitude to produce a distortion like effect
% Possibility for extension:
%       -different clipping shape
%       -clipping ranges (if in certain range of vals clip to a certain level)
%       -experiment with bigger amps eg.500, 1000...audiowrite will warn of clipping but could give interesting sounds
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters to vary the effect %
clip=0.1;  % clipping threshold 0-0.99
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

amp=1/clip;    % amplify coefficient
amp=amp-1; % this ensures max output is 0.99 and min is -0.99. Otherwise output is clipped anyway, experiment with bigger amps eg.500, 1000...

infile='acoustic.wav';
outfile='out_fuzz.wav';

% load a WAVE file samples into wave. Amplitude values are in the range [-1,+1]
% returns the sample rate (Fs) in Hertz used to encode the data
[wave,Fs] = audioread(infile);

%figure;
%plot(wave);
%before=fft(wave);
%figure;
%stem(before);

% determine number of samples
no_samples = size(wave);

% for each sample (is there a more efficient way of doing this???)
for i=1:no_samples

    % clip at both ends
    if (wave(i) > clip)
        wave(i) = clip;   
    end
    if (wave(i) < -clip)
        wave(i) = -clip;   
    end
    
    % amplify!
    wave(i)=amp*wave(i);
end

%figure;
%plot(wave);
%after=fft(wave);
%figure;
%stem(after);

% writes altered wave to a WAVE file
% sample rate of Fs Hz
audiowrite(outfile, wave,Fs);