% 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...wavwrite 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='sample.wav';
outfile='outfile.wav';

% load a WAVE file samples into wave. Amplitude values are in the range [-1,+1]
% returns the sample rate (Fs) in Hertz and the number of bits per sample (N) used to encode the data
[wave,Fs,N] = wavread(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 and is N-bit
wavwrite(wave,Fs,N,outfile);