% granulation.m
%f=fopen('a_male.m11');
%x=fread(f,'int16')';
%fclose(f);

clear all;
close all;

[filename,path] = uigetfile({'*.wav;*.waV;','Wav Files'; ...
            '*.*', 'All files (*.*)'}, ...
            'Select a sound file');
		if isequal(filename,0) | isequal(path,0)
			cd(savedir);
			return;
		end
		filenamepath = [path filename];

%[x, fs] = audioread('Toms_diner.wav');
[x, fs] = audioread(filenamepath);

figure(1)
plot(x);

doit = input('\nPlay Original Wav file? Y/[N]:\n\n', 's');

if doit == 'y',

playsound(x,fs);
end


Ly=length(x);  y=zeros(Ly,1);              %output signal

timex = Ly/fs;

% Constants
nEv=400; maxL=round(fs*0.02);  minL=round(fs*0.01);  Lw=round(fs*0.01);
% Initializations
L = round((maxL-minL)*rand(nEv,1))+minL;   %grain length
initIn = ceil((Ly-maxL)*rand(nEv,1));      %init grain
initOut= ceil((Ly-maxL)*rand(nEv,1));      %init out grain
a = rand(nEv,1);                           %ampl. grain
endOut=initOut+L-1;
% Synthesis
for k=1:nEv,
  grain=grainLn(x,initIn(k),L(k),Lw);
  figure(2)
  plot(grain);
  y(initOut(k):endOut(k))=y(initOut(k):endOut(k))+ grain;
end



figure(3) 
plot(y)


doit = input('\nPlay Granular Synthesied Wave? Y/[N]:\n\n', 's');

if doit == 'y',

playsound(y,fs);
end
